Turn Number into binary text

5

How do I get the representation of a Number (integer) in binary with JavaScript?

Ex:

47 = 00101111
    
asked by anonymous 04.11.2016 / 00:55

3 answers

5

If you want it to work generically, including negatives:

function dec2bin(dec) {
    return dec >= 0 ? dec.toString(2) : (~dec).toString(2);
}
console.log(dec2bin(47));
console.log(dec2bin(-47));

If you want to do a padding :

function dec2bin(dec) {
    var binario = dec >= 0 ? dec.toString(2) : (~dec).toString(2);
    var tamanho = binario.length > 32 ? 64 : binario.length > 16 ? 32 : binario.length > 8 ? 16 : 8;
    return ("0".repeat(tamanho) + binario).substr(-tamanho);
}
console.log(dec2bin(47));
console.log(dec2bin(-47));
console.log(dec2bin(12347));
console.log(dec2bin(5612347));
    
04.11.2016 / 01:24
6

As mentioned earlier, you can use .toString() and passing as argument 2 , which means base 2, radix 2 or binary.

To complete the leading zeros, just one more line of code, something like this:

function binarificar(nr){
    var str = nr.toString(2);
    return '00000000'.slice(str.length) + str;
}

console.log(binarificar(1));  // 00000001
console.log(binarificar(47)); // 00101111
    
04.11.2016 / 02:00
4

One option is this:

(47).toString(2)

The toString method, in Javascript, accepts on which basis you want to get the integer representation. In the above case it was in base 2.

    
04.11.2016 / 00:59