Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 652
DimC Avatar asked Mar 31 '12 09:03

DimC


1 Answers

convert to base 2:

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

access the characters (bits):

base2[0], base2[1], base2[3], etc... 
like image 78
nobody Avatar answered Sep 29 '22 16:09

nobody