Loading lesson path
&
Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^
Sets each bit to 1 if only one of two bits is 1 ~
<<
Shifts left by pushing zeros in from the right and let the leftmost bits fall off >>
Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off >>>
Shifts right by pushing zeros in from the left, and let the rightmost bits fall off
5 & 1
0101 & 0001 0001 5 | 1
0101 | 0001 0101 ~ 5 10 ~0101 1010 5 << 1 10 0101 << 1 1010
Formula
5 ^ 1Formula
0101 ^ 00010100 5 >> 1
0101 >> 1 0010 5 >>> 1
0101 >>> 1 0010
JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers. Before a bitwise operation is performed, JavaScript converts numbers to 32 bits signed integers. After the bitwise operation is performed, the result is converted back to 64 bits JavaScript numbers. The examples above uses 4 bits unsigned binary numbers. Because of this ~ 5 returns 10.
Since JavaScript uses 32 bits signed integers, it will not return 10. It will return -6.
00000000000000000000000000000101 (5)
11111111111111111111111111111010 (~5 = -6)A signed integer uses the leftmost bit as the minus sign.
When a bitwise AND is performed on a pair of bits, it returns 1 if both bits are 1.
0 & 0
0 & 1
1 & 0
1 & 1
4 bits example:
1111 & 0000 0000 1111 & 0001 0001 1111 & 0010 0010 1111 & 0100 0100
When a bitwise OR is performed on a pair of bits, it returns 1 if one of the bits is 1: