Reputation: 399
When I want to convert a binary string to a base 10 decimal (Like this: parseInt('0001010', 2)
), Javascript returns a decimal number, but a version in which the leading zeros mentioned in the example above have been disregarded. Is there any way to fix this?
Upvotes: 0
Views: 175
Reputation:
So supposing you have the number '00000101101101':
var number = '00000101101101';
var length = number.length;
var decimal_number = parseInt(number, 2);
// going back
var new_number = decimal_number.toString(2);
var new_length = new_number.length;
var n_zeros = length - new_length;
var zeros = (n_zeros >= 2 ? Array(n_zeros+1).join("0") : "0");
new_number = zeros + new_number;
Upvotes: 1
Reputation: 500307
The decimal representation has no way to keep track of leading zeros. If you wish to keep the leading zeros in the result, you need a fundamentally different approach (e.g. keeping the output as a string).
Alternatively, if you know the width of the result a priori, you could just pad it with leading zeros on output.
Upvotes: 1