Bitwise operations are hard to understand for some beginning programmers. So this post is to explain them easily and unforgettably.
Master Bitwise Operations in 10 Minutes
The devil is in the details because if you get it wrong, you get a different answer
What’s a bit and bit string?
A bit is the smallest unit of information that can be stored or manipulated on a computer. It consists of a single Boolean value (0 or 1).
A bit string is a sequence of bits. It can be used to represent sets or to manipulate binary data.
Bitwise AND (&)
The bitwise AND operator (
&) returns a
1 in each bit position for which the corresponding bits of both operands (input and mask) are
Y AND 1 = Y
Y AND 0 = 0
Therefore, to turn certain bits off,
AND can be used with a
0 .To leave a bit unchanged,
AND is used with a
Example: Masking on the higher bits (bits 4,5,6) the lower bits (bits 0,1,2, 3) unchanged.
Bitwise OR (|)
The bitwise OR operator (
|) returns a
1 in each bit position for which the corresponding bits of either or both operands(input and mask) are
Y OR 1 = 1
Y OR 0 = Y
Therefore, to make certain bits on,
OR can be used with a
1 .To leave a bit unchanged,
OR is used with a
Example: Masking on the lower bits (bits 0,1, 2, 3) the higher bits (bits 4, 5, 6) unchanged.
Bitwise exclusive OR (^)
The bitwise XOR operator (
^) returns a
1 in each bit position for which the corresponding bits of either but not both operands (input and mask) are
In another word, Bitwise exclusive OR sets 1 in each position where its operands have different bits, and 0 if they’re the same.
Y ^ 0 = Y
Y ^ a = 0
Left shift and Right shift
A bit shift moves each digit in a number’s binary representation left or right.
When shifting left, the most-significant bit is lost, and a 00 bit is inserted on the other end. When shifting right with a logical right shift, the least-significant bit is lost and a 00 is inserted on the other end.
Getting a bit
To querying the status of a bit, shift the number
n to the right, then bitwise AND with
（number >> n) & 1
Setting a bit
number |= 1 << n
Clearing a bit
Use the bitwise AND operator (
&) to clear a bit.
number &= ~(1 << n)
Toggle a bit
The XOR operator (
^) can be used to toggle a bit.
number ^= 1 << n