我有一个“布尔位数组”,
const array: boolean[] = [false, true, false, true]; // 0101
我该如何获得一个数字5?谢谢
我有一个“布尔位数组”,
const array: boolean[] = [false, true, false, true]; // 0101
我该如何获得一个数字5?谢谢
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 Miaotrue, false, true
。如何方便地控制输出数组的大小呢?例如如果我输入4,它将显示false, true, false, true
;如果我输入5,它将显示false, false, true, false, true
。 - Hongbo Miaowhile a.length < desired a.unshift(false)
。 - georg(res, x) => res << 1 | x
发生了什么。我知道这是一个按位或操作。 - xinthosex
(1或0)。例如,假设res=6(110),x=1,则res<<1
为12(1100),res<<1|x
为13(1101)。 - georgconst 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
这对我在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
};
并没有回答问题,但涉及到了将布尔值数组表示为数字并进行转换的相关主题。
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
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
parseInt(array.map(i => i+0).join(''), 2)
//5`parseInt(array.map(i => i+0).join(''), 2)
//5 - A1exandr Belan