Javascript Bitwise Operation

Introduction

Signed integers use the first 31 of the 32 bits to represent the numeric value of the integer.

The 32nd bit represents the sign of the number: 0 for positive or 1 for negative.

Positive numbers are stored in true binary format, with each of the 31 bits representing a power of 2, starting with the first bit (called bit 0).

If any bits are unused, they are filled with 0 and essentially ignored.

For example, the number 18 is represented as 00000000000000000000000000010010, or more succinctly as 10010.

These are the five most significant bits and can be used, by themselves, to determine the actual value.

Negative numbers are stored in binary code in a format called two's complement.

The two's complement of a number is calculated in three steps:

  • Determine the binary representation of the absolute value. For example, to find -18, first determine the binary representation of 18.
  • Find the one's complement of the number, which essentially means that every 0 must be replaced with a 1, and vice versa.
  • Add 1 to the result.

Using this process to determine the binary representation -18, start with the binary representation of 18, which is the following:

0000 0000 0000 0000 0000 0000 0001 0010 

Next, take the one's complement, which is the inverse of this number:

1111 1111 1111 1111 1111 1111 1110 1101 

Finally, add 1 to the one's complement as follows:

1111 1111 1111 1111 1111 1111 1110 1101 
                                      1 
---------------------------------------- 
1111 1111 1111 1111 1111 1111 1110 1110 

So the binary equivalent of -18 is 11111111111111111111111111101110.

Keep in mind that you have no access to bit 31 when dealing with signed integers.

Javascript does its best to keep all of this information from you.

When outputting a negative number as a binary string, you get the binary code of the absolute value preceded by a minus sign:

let num = -18; 
console.log(num.toString(2));  // "-10010" 

When you convert the number -18 to a binary string, the result is -10010.




PreviousNext

Related