Javascript Word To Binary to Array of Bits

Viewed 198

I have this code // Fiddle : https://jsfiddle.net/7buscnhw/

// Word to bits func
function dec2bin(dec) {
  return (dec >>> 0).toString(2);
}
// binary to bit array
function bin2array(bin) {
    let Bitarr = []
    for(let i = 0; i < bin.length; ++i)
  Bitarr[i] = (bin >> i) & 1;
  return Bitarr;
}


R24011 = dec2bin(10);

Bits = bin2array(R24011);

msg = {
    R24011: R24011,
    BitArray: Bits
}
console.log(msg)

It correctly outputs 1010 for Ten in binary, but when I push it to an array I get [0,1,0,0]

I'm sure it'll be something stupid but I cant figure out what I've done wrong.

2 Answers

You can directly use spread syntax to convert the binary string to an array.

function dec2bin(dec) {
  return (dec >>> 0).toString(2);
}
function bin2array(bin) {
  return [...bin].map(Number);
}
R24011 = dec2bin(10);
console.log(R24011)
Bits = bin2array(R24011);
console.log(Bits)

You pass bin (which is a string "1010") and apply >> to it, which makes Javascript convert it to a number in base 10, resulting in 1010 (one thousand and ten), which is binary 1111110010. Then, you convert that one to binary once again, using only four bits and in reversed order, which results in [0,1,0,0]

If you want to convert a number (not a string) to an array bits (and avoid built-ins), you can do that like this:

function num2bits(number) {
    let Bitarr = []

    while (number) {
        Bitarr.unshift(number & 1);
        number >>= 1
    }
    return Bitarr;
}

console.log(num2bits(10))

With built-ins this is as simple as

bits = [...yourNumber.toString(2)].map(Number)
Related