Javascript - Operator Bitwise Operators

Introduction

Bitwise Operators works with numbers on the bits.

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.

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 

Then, 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 

-18 is 11111111111111111111111111101110 in binary.

ECMAScript displays a negative number as a binary string, and you get the binary code of the absolute value preceded by a minus sign:

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

Using bitwise operator on a nonnumeric value will convert the value into a number using the Number() function and then the bitwise operation is applied.

Related Topics