'Number.toString(2) is omitting 0's from end in javascript?
I am trying to reverse the 32-bit unsigned integer by converting it to a string first but the toString(2) function is committing the zero's from the end and because of it the output I am getting is wrong.
MyCode:
var reverseBits = function(n) {
let reverserN=(n>>>0).toString(2).split('').reverse().join('');
console.log(reverserN)
return parseInt(reverserN,2)
};
Output:
Your input
00000010100101000001111010011100
stdout
00111001011110000010100101 //0's omitted from the end
Output
15065253 (00000000111001011110000010100101)
Expected
964176192 (00111001011110000010100101000000)
And, if I try to use BigInt then it is giving me n at the end. Like this 00111001011110000010100101n.
Why 0's are omitted? And how can I stop it from omitting 0's from the end?
Solution 1:[1]
By adding padEnd(32,0) after join('') works. Which simply added 0's at the end to the resulting string so that it reaches a given length.
Mycode:
var reverseBits = function(n) {
let reverserN=(n>>>0).toString(2).split('').reverse().join('').padEnd(32,0);
console.log(reverserN);
return parseInt(reverserN,2)
};
Output:
00111001011110000010100101000000 //6 0's at the end of the string
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Harsh Mishra |
