2

I'm using the solution provided here Read bit value to convert 1 byte (8 bit - unsigned number from 0 to 255) to a boolean array, E.g 118 gives me:

boolArray = [false, true, true, false, true, true, true, false]

Now I need to convert it back to the decimal representation, If i create a binary from boolArray like this:

    binObj = []
    OutObj.map((obj) => {
      BoolToInt = obj.isActive ? 1 : 0
      binObj.push(BoolToInt)
    })
    binary = binObj.toString().replaceAll(',', '') // =>  01101110

how can I convert the binary "01101110" to decimal value 118?

If I use parseInt the result is 110 not 118

 parseInt('01101110', 2) => 110

am I doing something wrong?

I would get back 118 from 01101110, not 110.

6
  • FYI, "false", "true" are strings, (not boolean false, true) and will all evaluate to true. Commented Dec 12, 2022 at 9:06
  • Well 1101110 is 110 and not 118. (1*64+1*32+0*16+1*8+1*4+1*2+0*1 = 64+32+8+4+2 = 110). 118 is the reverted direction 1110110. read the array backwards. Commented Dec 12, 2022 at 9:10
  • I'm converting true to 1 and false to 0 Commented Dec 12, 2022 at 9:10
  • @RokoC.Buljan you'r right, edited Commented Dec 12, 2022 at 9:20
  • @MoxxiManagarm yes! reversing the array did the trick! Commented Dec 12, 2022 at 9:20

1 Answer 1

3

A more compact way of doing decimal<->binary boolean arrays:

console.log([...(118).toString(2)].map(i=>i==='1'))
console.log(
  parseInt([true,true,true,false,true,true,false].map(i=>+i).join(''),2)
)

Sign up to request clarification or add additional context in comments.

1 Comment

Number() isn't really necessary here because 118 already is a number. [...(118).toString(2)] or [...118..toString(2)] will do.

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.