Way To Add Leading Zeroes To Binary String In JavaScript
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) // yiel
Solution 1:
It's as simple as
var n = num.toString(2);
n = "00000000".substr(n.length) + n;
Solution 2:
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;
}
Solution 3:
Try something like this ...
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
... then use it as ...
pad(num.toString(2), 8);
Post a Comment for "Way To Add Leading Zeroes To Binary String In JavaScript"