Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert "boolean bit array" to number in Typescript

I have a "boolean bit array",

array:Array = [false, true, false, true]; // 0101

How can I get a number 5? Thanks

like image 858
Hongbo Miao Avatar asked Feb 09 '16 16:02

Hongbo Miao


People also ask

How do you convert a boolean to a number in TypeScript?

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).

How do you convert boolean to array?

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.

How do you convert a boolean to a string in TypeScript?

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.


1 Answers

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)
like image 93
georg Avatar answered Oct 05 '22 07:10

georg