javascript - Konvertera "boolean bit array" till nummer i Typescript
Jag har en "boolean bit-array".
const array: boolean[] = [false, true, false, true]; // 0101
Hur kan jag få en nummer 5? Tack
Svar #1
Jag kan inte TS, i ren JS är det
a = [false, true, false, true]
b = a.reduce((res, x) => res << 1 | x)
alert(b)Att göra motsatsen (dvs. nummer till array):
b = 5
a = b ? [] : [false]
while(b) {
a.push((b & 1) === 1)
b >>= 1
}
alert(a)eller
b = 5
a = b.toString(2).split('').map(x => x === '1');
alert(a)Svar #2
Detta fungerar för mig med 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
};
