43

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

1
  • An array of bits it not a byte. And an array of 0's and 1's is probably just an array of int. Commented Mar 31, 2012 at 9:37

9 Answers 9

84

convert to base 2:

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

access the characters (bits):

base2[0], base2[1], base2[3], etc...
Sign up to request clarification or add additional context in comments.

8 Comments

Fantastic, this works so well! I was looking at bit-shift operations for ages but this is much faster. Many thanks!!
What does wrapping yourNumber in parentheses do? If I run var base2 = 5.toString(2); it won't work, so I'm curious... Thanks!
if you have integer literal, e,g you can 21..toString(2). No need to convert to Number object.
It should be noted that the resulting string is not padded with leading zeros. If you wanted an 8-bit string with leading zeros you could use ("00000000" + number.toString(2)).slice(-8), for example.
The original question requests a right-to-left parsing of the split string: var base2 = (yourNumber).toString(2).reverse()
|
14

Short (ES6)

Shortest (32 chars) version which fill last bits by zero. I assume that n is your number, b is base (number of output bits):

[...Array(b)].map((x,i)=>n>>i&1)

let bits = (n,b=32) => [...Array(b)].map((x,i)=>(n>>i)&1);

let Bitarr = bits(22,8);

console.log(Bitarr[0]); // = 0
console.log(Bitarr[1]); // = 1
console.log(Bitarr[2]); // = 1
console.log(Bitarr[3]); // = 0
console.log(Bitarr[4]); // = 1

Comments

10
var a = 22;
var b = [];

for (var i = 0; i < 5; i++)
  b[i] = (a >> i) & 1;

alert(b);

Assuming 5 bits (it seemed from your question), so 0 <= a < 32. If you like you can make the 5 larger, upto 32 (bitshifting in JavaScript works with 32 bit integer).

Comments

3

This should do

for(int i = 0; i < 32; ++i)
  Bitarr[i] = (my_int >> i) & 1;

Comments

3

You can convert your integer to a binary String like this. Note the base 2 parameter.

var i = 20;
var str = i.toString(2); // 10100

You can access chars in a String as if it were an array:

alert(str[0]); // 1
alert(str[1]); // 0
etc...

Comments

2

Building up on previous answers: you may want your array to be an array of integers, not strings, so here is a one-liner:

(1234).toString(2).split('').map(function(s) { return parseInt(s); });

Note, that shorter version, (11).toString(2).split('').map(parseInt) will not work (chrome), for unknown to me reason it converts "0"s to NaNs

4 Comments

map(parseInt) doesn't work, for Array.prototype.map() provides 3 args for its callback, of which the 2nd is the array index. parseInt() expects 2 args, of which the 2nd is the radix.
(11).toString(2).split('').map(val=>parseInt(val))
I just used the @HJCross code to create an array of bitmask values from a number: (11).toString(2).split("").reverse().map((v, i) => (parseInt(v) ? Math.pow(2, i) : 0)).filter(v => v != 0) returns [1, 2, 8]. There doesn't seem to be a way to format code nicely in comments here. Am I missing something?
bits as bools version: (2).toString(2).padStart(8,0).split('').map(function(x){return (x == 1)}) with padding
1

In addition, this code gives 32length array

function get_bits(value){
        var base2_ = (value).toString(2).split("").reverse().join("");
        var baseL_ = new Array(32 - base2_.length).join("0");
        var base2 = base2_ + baseL_;
        return base2;
    }
1 => 1000000000000000000000000000000
2 => 0100000000000000000000000000000
3 => 1100000000000000000000000000000

1 Comment

This gives strings of length 31. The third line should be: var baseL_ = new Array(33 - base2_.length).join("0");
1

You might do as follows;

var n = 1071,
    b = Array(Math.floor(Math.log2(n))+1).fill()
                                         .map((_,i,a) => n >> a.length-1-i & 1);
console.log(b);

1 Comment

this doesn't seem to work for numbers bigger than 32 bits, due to the bitwise operations
1

just for the sake of refernce:

(121231241).toString(2).split('').reverse().map((x, index) => x === '1' ? 1 << index : 0).reverse().filter(x => x > 0).join(' + ');

would give you:

67108864 + 33554432 + 16777216 + 2097152 + 1048576 + 524288 + 65536 + 32768 + 16384 + 4096 + 1024 + 512 + 256 + 128 + 8 + 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.