Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to add leading zeroes to binary string in JavaScript [duplicate]

I've used .toString(2) to convert an integer to a binary, but it returns a binary only as long as it needs to be (i.e. first bit is a 1).

So where:

num = 2;
num.toString(2) // yields 10. 

How do I yield the octet 00000010?

like image 560
zahabba Avatar asked Dec 24 '14 20:12

zahabba


2 Answers

It's as simple as

var n = num.toString(2);
n = "00000000".substr(n.length) + n;
like image 199
Joe Thomas Avatar answered Oct 02 '22 09:10

Joe Thomas


You could just use a while loop to add zeroes on the front of the result until it is the correct length.

var num = 2,
    binaryStr = num.toString(2);

while(binaryStr.length < 8) {
    binaryStr = "0" + binaryStr;
}
like image 28
forgivenson Avatar answered Oct 02 '22 08:10

forgivenson