2

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.

1
  • 3
    "but when I push it to an array" - where do you do this? --- Edit: ah I see. It's the result of bin2array(dec2bin(10)) Commented Jul 8, 2021 at 14:57

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This gets its done. is there an easy way to reverse the array direction. for example, Bitarr[0] to be the 1/0 and Bitarr[3] to be 8. Ah nevermind ofc there is .reverse
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.