15

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?

zahabba
  • 2,921
  • 5
  • 20
  • 33

3 Answers3

40

It's as simple as

var n = num.toString(2);
n = "00000000".substr(n.length) + n;
Joe Thomas
  • 5,807
  • 6
  • 25
  • 36
  • 13
    Now you can use standard 'n.padStart(paddingSize, '0');' – DevMultiTech Dec 05 '19 at 09:34
  • @DevMultiTech, you should make yours an answer and it should be the chosen one. function pad(v,s=8){return v.toString(2).padStart(s, '0'); 1. pad(1); /* '00000001' */ 2. pad(1,2); /* '01' */ – Beez Aug 21 '21 at 00:23
6

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;
}
Jett
  • 17
  • 6
forgivenson
  • 4,394
  • 2
  • 19
  • 28
2

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);
rfornal
  • 5,072
  • 5
  • 30
  • 42