在Typescript中将"布尔位数组"转换为数字

6

我有一个“布尔位数组”,

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

我该如何获得一个数字5?谢谢


parseInt(array.map(i => i+0).join(''), 2) //5`parseInt(array.map(i => i+0).join(''), 2) //5 - A1exandr Belan
5个回答

8
我不了解TS,在纯JS中,它是这样的:

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

要进行反向操作(即数字转换为数组):

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

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

alert(a)

或者

b = 5

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

alert(a)


res << 1 | x, 0,这个 , 0 是什么意思?因为如果我改成 res << 1 | x,它还是能正常工作的。谢谢。 - Hongbo Miao
再次感谢,我该如何保留第一个“false”呢?现在的结果是true, false, true。如何方便地控制输出数组的大小呢?例如如果我输入4,它将显示false, true, false, true;如果我输入5,它将显示false, false, true, false, true - Hongbo Miao
1
@HongboMiao:只需添加任意数量的假值即可:while a.length < desired a.unshift(false) - georg
我真的不理解 reduce 函数中 (res, x) => res << 1 | x 发生了什么。我知道这是一个按位或操作。 - xinthose
1
@xinthose:它将累加器向左移动一位,并将最右边的位设置为x(1或0)。例如,假设res=6(110),x=1,则res<<1为12(1100),res<<1|x为13(1101)。 - georg

0
我会使用简单的数字/基数和字符串分割/连接函数来完成这个任务。
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)

使用boolArrToNumber,您可以验证:

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

0

这对我在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
};

0

并没有回答问题,但涉及到了将布尔值数组表示为数字并进行转换的相关主题。

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() 用于替代 reduce(),以消除将数字转换回布尔值时需要反转数组的需求。它的初始值为1而不是0,以保留数组的大小并保持数组起始的false值。它的工作方式就像我们传递了长度为+1的数组,其第一个值为true。这会增加1位,但消除了后续检查数组长度的需要。在通过 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

0
添加一个简单的解决方案。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接