6

I have a "boolean bit array",

const array: boolean[] = [false, true, false, true]; // 0101

How can I get a number 5? Thanks

1
  • parseInt(array.map(i => i+0).join(''), 2) //5 Commented Nov 15, 2021 at 16:19

5 Answers 5

9

I don't know TS, in pure JS it's

a = [false, true, false, true]
b = a.reduce((res, x) => res << 1 | x)
alert(b)

To do the opposite (i.e. number to array):

b = 5
a = b ? [] : [false]

while(b) {
  a.push((b & 1) === 1)
  b >>= 1
}

alert(a)

or

b = 5

a = b.toString(2).split('').map(x => x === '1');

alert(a)

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

5 Comments

res << 1 | x, 0, what is this , 0? Because if I change to res << 1 | x, it still works. thanks
thanks again, how can I reserve the first false too? right now the result is true,false,true. How can I control the size of output array easily, like if I give a 4, it shows false,true,false,true; if I give a 5, it shows false,false,true,false,true
@HongboMiao: just add as many falses as you want: while a.length < desired a.unshift(false).
I really do not understand what is happening in the reduce function (res, x) => res << 1 | x. I know it is a bitwise OR operation.
@xinthose: it shifts the accumulator to the left by one and sets the rightmost bit to x (1 or 0). For example, let res=6 (110) and x = 1, then res<<1 is 12 (1100) and res<<1|x is 13 (1101)
0

This works for me with typescript.

async maskBoolToInt(boolArray:boolean[]){
    let debugmode = true;
    if(debugmode){
        console.log('Debug : "maskBoolToInt"  Started');
        console.log('boolArray = ' + boolArray);
    }
    let bitArray:number[] = [];
    boolArray.forEach((element) => {
        bitArray.push(+element);    //convert bool to bit
    });
    if(debugmode){
        console.log('bitArray = ' + bitArray);
    }
    let result: any = bitArray.reduce((accumulator: number, currentValue: number) => accumulator << 1 | currentValue); //bitwise conversion to integer
    if(debugmode){
        console.log('result = ' + result);
        console.log('Debug : "maskBoolToInt"  Finished');
    }
    return result
};

Comments

0

I would use simple number/radix with string split/join function to do that.

const numberToBoolArr = (n: number): Array<boolean> => (n).toString(2).split('').map(r => r === '1')
const boolArrToNumber = (arr: Array<boolean>): number =>
    parseInt(arr.map(r => r ? '1' : '0').join(''), 2)

With the boolArrToNumber, you can verify that:

console.log(boolArrToNumber([false, true, false, true])) // 5

Comments

0

Doesn't answer the question, but touches on the related topic of representing an array of boolean values as a number and converting it back.

const boolsToNum = (bools: boolean[]) => { 
    return bools.reduceRight((res, bool) => res << 1 | +bool, 1)
}
const numToBools = (num: number) => {
    const bools = []
    while (num > 1) {
        bools.push((num & 1) === 1)
        num >>= 1
    }
    return bools
}

reduceRight() is used instead of reduce() to remove the need of reversing the array when converting a number back to bools. Its initial value used as 1 instead of 0 to preserve the size of array and to keep array starting false values. It works as if we passed in the array of +1 length, which first value is true. Costs 1 bit but removes the need of checking array length later. This bit is dropped when converting back by while (num > 1)

const array:Array<boolean> = [false, true, false, true]; // 0101

console.log(array, 'original')
const num = boolsToNum(array)

console.log(num, 'compressed')
console.log(numToBools(num), 'uncompressed')

// (4) [false, true, false, true] original
// 26 compressed
// (4) [false, true, false, true] uncompressed

Comments

0

Add a naive solution

const booleanArrayToInt = (array: boolean[]) => {
  let res = 0;
  for (let i = 0; i < array.length; i++) {
    if (array[array.length - i - 1]) {
      res += 2 ** i;
    }
  }
  return res;
};

console.log(booleanArrayToInt([false, true, false, true])); // 5

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.