41

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

John Carter
  • 53,924
  • 26
  • 111
  • 144
DimC
  • 495
  • 1
  • 5
  • 12

9 Answers9

81

convert to base 2:

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

access the characters (bits):

base2[0], base2[1], base2[3], etc...
nobody
  • 10,599
  • 4
  • 26
  • 43
  • 4
    Fantastic, this works so well! I was looking at bit-shift operations for ages but this is much faster. Many thanks!! – DimC Mar 31 '12 at 10:01
  • U wrote "array of bits", so ---> var base2 = (yourNumber).toString(2).split(''); <--- will give you each character (string, you still have to parseInt) within an array. – sebilasse May 11 '14 at 14:08
  • 1
    What does wrapping _yourNumber_ in parentheses do? If I run `var base2 = 5.toString(2);` it won't work, so I'm curious... Thanks! – Levi Mootz Dec 18 '15 at 04:41
  • Of all the complicated ways to figure out the value of a bit in a byte, this is by far the simplest! Thanks :) – Tremendus Apps Dec 21 '17 at 23:29
  • 1
    if you have integer literal, e,g you can `21..toString(2)`. No need to convert to Number object. – Cholthi Paul Ttiopic Feb 06 '18 at 12:45
  • 5
    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. – Steven Rands Apr 26 '18 at 10:32
  • 3
    The original question requests a right-to-left parsing of the split string: `var base2 = (yourNumber).toString(2).reverse()` – Sideways S Sep 20 '18 at 22:41
  • This helped me with the BinaryGap test in Codility. Thank you so much ♥! – Jeancarlo Fontalvo Oct 10 '18 at 21:34
12

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
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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).

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
3

This should do

for(int i = 0; i < 32; ++i)
  Bitarr[i] = (my_int >> i) & 1;
Salepate
  • 327
  • 3
  • 11
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...
Jivings
  • 22,834
  • 6
  • 60
  • 101
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

Lex Podgorny
  • 2,598
  • 1
  • 23
  • 40
  • 2
    `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_. – Alexander Gromnitsky Nov 21 '16 at 11:01
  • 1
    ```(11).toString(2).split('').map(val=>parseInt(val))``` – HJ Cross May 06 '17 at 04:54
  • 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? – Sideways S Sep 20 '18 at 22:49
  • bits as bools version: `(2).toString(2).padStart(8,0).split('').map(function(x){return (x == 1)})` with padding – Karanko Nov 02 '19 at 17:23
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
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
  • This gives strings of length 31. The third line should be: var baseL_ = new Array(33 - base2_.length).join("0"); – Sam Jul 10 '15 at 12:28
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);
Redu
  • 25,060
  • 6
  • 56
  • 76
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
Trident D'Gao
  • 18,973
  • 19
  • 95
  • 159