Introduction to Bit Manipulation
Bit manipulation is the act of algorithmically manipulating bits or binary digits.
Convert Decimal to Binary
Explanation
Convert Binary to Decimal
Explanation
1's Complement
Explanation
2's Complement
Explanation
Bitwise AND Operator (&)
Explanation
This is the truth table for the bitwise AND operator
A | B | A & B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
Example:
A = 5 # 101
B = 3 # 011
A & B = 1 # 001
# Calculation
101
011
---
001
💡
Trick to remember: 1 & 1 = 1, else 0
Bitwise OR Operator (|)
Explanation
This is the truth table for the bitwise OR operator
A | B | A | B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 1 |
Example:
A = 5 # 101
B = 3 # 011
A | B = 7 # 111
# Calculation
101
011
---
111
💡
Trick to remember: 0 | 0 = 0, else 1
Bitwise XOR Operator (^)
Explanation
This is the truth table for the bitwise XOR operator
A | B | A ^ B |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Example:
A = 5 # 101
B = 3 # 011
A ^ B = 6 # 110
# Calculation
101
011
---
110
This is the binary representation of 6
💡
Trick to remember:
1 ^ 1 = 0
, 0 ^ 0 = 0
, else 1Bitwise NOT Operator (~)
Explanation
This is the truth table for the bitwise NOT operator
A | ~A |
---|---|
0 | 1 |
1 | 0 |
Example:
A = 5 # 101
~A = -6 # 010
# Calculation
101
---
010
This is the binary representation of -6
How? 2's complement of 6 is 010
💡
Trick to remember: 1 becomes 0, 0 becomes 1
Left Shift Operator (<<)
Explanation
Left shift operator shifts the bits to the left by n positions
Example:
A = 5 # 101
A << 1 = 10 # 1010
Right Shift Operator (>>)
Explanation
Right shift operator shifts the bits to the right by n positions
Example:
A = 5 # 101
A >> 1 = 2 # 10