Binary Numbers

Binary numbers with only one bit set is easy to understand:

Binary Representation Decimal value
00000000000000000000000000000001 1
00000000000000000000000000000010 2
00000000000000000000000000000100 4
00000000000000000000000000001000 8
00000000000000000000000000010000 16
00000000000000000000000000100000 32
00000000000000000000000001000000 64

Setting a few more bits reveals the binary pattern:

Binary Representation Decimal value
00000000000000000000000000000101 5 (4 + 1)
00000000000000000000000000001101 13 (8 + 4 + 1)
00000000000000000000000000101101 45 (32 + 8 + 4 + 1)

JavaScript binary numbers are stored in two's complement format.

This means that a negative number is the bitwise NOT of the number plus 1:

Binary Representation Decimal value
00000000000000000000000000000101 5
11111111111111111111111111111011 -5
00000000000000000000000000000110 6
11111111111111111111111111111010 -6
00000000000000000000000000101000 40
11111111111111111111111111011000 -40

Converting Decimal to Binary

Example

function dec2bin(dec){
  return (dec >>> 0).toString(2);
}

Converting Binary to Decimal

Example

function bin2dec(bin){
  return parseInt(bin, 2).toString(10);
}
 



Practice Excercise Practice now