Reputation: 74
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.
Upvotes: 2
Views: 235
Reputation: 8107
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)
)
Upvotes: 3