I convert a decimal number into binary. My number is 66. I convert it like:
let bin1 = Number(66).toString(2);
console.log(`Result: ${bin1}, Length: ${bin1.length}`);
The result I get is bin1 = 1000010. So I get only 7 bits of the byte. I want to get all 8 bits of byte. So, I should get 01000010. What should I do to get so?
3
Answers
Insert zero’s until the stringified value length is a multiple of 8. For example:
You will have to pad your number:
Here is a formatter with documentation:
toString(2)
is unaware of the notion of byte, which is why the returned string does not necessarily have a number of digits that is a multiple of 8. It is expected that the returned string will always start with a "1", except when the input integer is 0 (assuming unsigned integers).You can use
padStart
to pad the string with the zeroes you need to get a multiple of 8: