简体   繁体   中英

Javascript - convert binary to decimal

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, Eg 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.

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) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM