I have a "boolean bit array",
array:Array = [false, true, false, true]; // 0101
How can I get a number 5? Thanks
Use the Number object to convert a boolean to a number in TypeScript, e.g. const num = Number(true) . When used as a function, Number(value) converts a value to a number. If the value cannot be converted, it returns NaN (not a number).
To convert a Boolean array a to an integer array, use the a. astype(int) method call. The single argument int specifies the desired data type of each array item.
Use the String object to convert a boolean to a string in TypeScript, e.g. const str = String(bool) . When used as a function, the String object converts the passed in value to a string and returns the result. Copied! The String function takes a value as a parameter and converts it to a string.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With