javascript interactive

JavaScript Interactive — a console crash course


2.7 Bitwise Operations

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.
>>>
(0x01 | 0x03).toString(2)
"11"
The bitwise operators | (OR), & (AND), ^ (XOR) and ~ (NOT) operate on a 32 bit integer representation of a number. Using toString(2) allows printing the resulting number in binary format.
>>>
(0x01 & 0x03).toString(2)
"1"
>>>
(0x01 ^ 0x03).toString(2)
"10"
>>>
(~0xECA86420).toString(16)
"13579bdf"
When using binary negation in particular, care must be taken to avoid unneeded conversions to and from the 64 bit floating-point representation of numbers, since this will often result in a negative number instead of the expected bit sequence.
>>>
(0xFFFF >> 4).toString(16)
"fff"
The << (left shift), >> (signed right shift) and >>> (unsigned right shift) operators allow moving the bits a number of steps in either direction.
>>>
var a = 1; a <<= 2; print(a);

  
The bitwise operators are also available as assignment operators: |=, &=, ^=, <<=, >>= and >>>=.
>>>

Index 1 2 3 4 5 6 7 8