Bitwise Operators#
Bitwise operators are used for performing operations on binary numbers, each with its own set of unique behaviors and laws.
- Bitwise AND (&): Returns a one in each bit position if bits of both operands are ones.
5 & 3;
// Outputs: 1
// Explanation: 0101 & 0011 = 0001
Identity Law : For any number a & a = a.
5 & 5;
// Outputs: 5
// Explanation: 0101 & 0101 = 0101
- Bitwise OR (|): Returns a one in each bit position if bits of either operand is one.
5 | 3;
// Outputs: 7
// Explanation: 0101 | 0011 = 0111
Identity Law : For any number a | a, it is left unchanged.
5 | 5;
// Outputs: 5
// Explanation: 0101 | 0101 = 0101
- Bitwise XOR (^): Returns a one in each bit position if bits of one operand is one and the other operand is zero. If they are opposite, they will turn to 1. If they are equal operands then the output will be 0.
5 ^ 3;
// Outputs: 6
// Explanation: 0101 ^ 0011 = 0110
Identity Law : For any number a ^ a, it is set to 0.
5 ^ 5;
// Outputs: 0
// Explanation: 0101 ^ 0101 = 0000
- Bitwise NOT (~): Inverts the bits of its operand. In binary, there is a way to represent negative numbers called the two’s complement system.
To find the two’s complement of a binary number (which represents its negative value):- Invert all the bits of the number (change 0s to 1s and 1s to 0s).
- Add 1 to the resulting number.
~5;
// Outputs: -6
// Explanation: ~0101 = 1010
// (in 32-bit, this is the two's complement representation of -6)
Inversion Law : For any number ~(~a), you get back a.
~0;
// Outputs: -1
// Explanation: ~0000 = 1111
// (in 32-bit, this is the two's complement representation of -1)
- Left shift (<<): Shifts its first operand in binary representation the number of bits to the left specified in the second operand, shifting in zeros from the right.
5 << 1;
// Outputs: 10
// Explanation: 0101 << 1 = 1010
- Sign-propagating right shift (>>): Shifts the first operand in binary representation the number of bits to the right specified in the second operand, discarding bits shifted off.
5 >> 1;
// Outputs: 2
// Explanation: 0101 >> 1 = 0010
- Zero-fill right shift (>>>): Shifts the first operand in binary representation the number of bits to the right specified in the second operand, discarding bits shifted off, and shifting in zeros from the left.
-5 >>> 1;
// Outputs: 2147483645
// Explanation: Represents shifting of the two's complement
// binary representation of -5