Transform Number into binary text

Asked

Viewed 1,743 times

5

How to achieve the representation of a Number (integer) in binary with Javascript?

Ex:

47 = 00101111

3 answers

6


If you want it to work in a generic way, 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 make 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));

I put in the Github for future reference.

  • It fit my function perfectly. Test.assertEquals worked well =)

6

As already mentioned you can use the .toString() and passing as an argument 2, which means base 2, Radix 2 or binary.

To complete the zeroes on the left just need 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

4

One option is this:

(47).toString(2)

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.