When a bitwise AND operation is performed on a pair of bits, it returns 1 only if both bits are 1.
Here’s a one-bit example:
Operation |
Result |
0 & 0 |
0 |
0 & 1 |
0 |
1 & 0 |
0 |
1 & 1 |
1 |
Here’s a 4-bit example:
When a bitwise OR operation is applied to a pair of bits, it returns 1 if at least one of the bits is 1.
Here’s a one-bit example:
Operation |
Result |
0 | 0 |
0 |
0 | 1 |
1 |
1 | 0 |
1 |
1 | 1 |
1 |
4 bits example:
Operation |
Result |
1111 | 0000 |
1111 |
1111 | 0001 |
1111 |
1111 | 0010 |
1111 |
1111 | 0100 |
1111 |
When a bitwise XOR operation is applied to a pair of bits, it returns 1 if the bits are different.
Here’s a one-bit example:
Operation |
Result |
0 ^ 0 |
0 |
0 ^ 1 |
1 |
1 ^ 0 |
1 |
1 ^ 1 |
0 |
4 bits example:
Operation |
Result |
1111 ^ 0000 |
1111 |
1111 ^ 0001 |
1110 |
1111 ^ 0010 |
1101 |
1111 ^ 0100 |
1011 |
Bitwise AND returns 1 only when both bits are 1.
Decimal |
Binary |
5 |
00000000000000000000000000000101 |
1 |
00000000000000000000000000000001 |
5 & 1 |
00000000000000000000000000000001 (1) |
let x = 5 & 1; |
Bitwise OR returns 1 if at least one of the bits is 1.
Decimal |
Binary |
5 |
00000000000000000000000000000101 |
1 |
00000000000000000000000000000001 |
5 | 1 |
00000000000000000000000000000101 (5) |
let x = 5 | 1; |
Bitwise XOR returns 1 when the bits are different.
Decimal |
Binary |
5 |
00000000000000000000000000000101 |
1 |
00000000000000000000000000000001 |
5 ^ 1 |
00000000000000000000000000000100 (4) |
let x = 5 ^ 1; |
Decimal |
Binary |
5 |
00000000000000000000000000000101 |
~5 |
11111111111111111111111111111010 (-6) |
let x = ~5; |
This is a zero-fill left shift, where one or more zero bits are added from the right, causing the leftmost bits to drop off.
Decimal |
Binary |
5 |
00000000000000000000000000000101 |
5 << 1 |
00000000000000000000000000001010 (10) |
let x = 5 << 1; |
This is a sign-preserving right shift, where copies of the leftmost bit are added from the left, causing the rightmost bits to drop off.
Decimal |
Binary |
-5 |
11111111111111111111111111111011 |
-5 >> 1 |
11111111111111111111111111111101 (-3) |
let x = –5 >> 1; |