javascriptbinary

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) // yields 10. 

How do I yield the octet 00000010?


Solution

  • It's as simple as

    var n = num.toString(2);
    n = "00000000".substr(n.length) + n;
    

    Update September 2024

    More idiomatically, it can now be written as:

     n.padStart(8, '0')
    

    thanks to @DevMultiTech