DimC DimC - 15 days ago 6
Javascript Question

Javascript - convert integer to array of bits

I am trying in javascript to convert an integer (which I know will be between 0 and 32), to an array of 0s and 1s. I have looked around but couldn't find something that works..

So, if I have an integer as 22 (binary 10110), I would like to access it as:

Bitarr[0] = 0
Bitarr[1] = 1
Bitarr[2] = 1
Bitarr[3] = 0
Bitarr[4] = 1


Any suggestions?
Many thanks

Answer

convert to base 2:

var base2 = (yourNumber).toString(2);

access the characters (bits):

base2[0], base2[1], base2[3], etc...