๐ง What Are Bitwise Operators?
Bitwise operators work on bits (0s and 1s) of integers at the binary level.
They are used to perform operations like AND, OR, XOR, NOT, etc., bit-by-bit.
๐งฉ Imagine You Have Blocks
Letโs say you have numbers made out of LEGO blocks โ but only with 1s and 0s. Like this:
5
= ๐งฑ 1 0 13
= ๐งฑ 0 1 1
These are binary numbers โ the way computers think!
๐ง What is a Bit?
- A bit is just a 1 or 0 โ like YES or NO.
- Computers love bits. They speak only in 1s and 0s!
๐ฎ Bitwise Operators
๐ 1. Bitwise AND (&
) โ “Both must be YES”
Rule: Only give 1 if BOTH blocks are 1.
5: 1 0 1
& 3: 0 1 1
----------
0 0 1 โ 1
๐ฃ โOnly the last bits are both 1. So answer is 1!โ
๐ 2. Bitwise OR (|
) โ “Anyone says YES?”
Rule: Give 1 if at least one block is 1.
5: 1 0 1
| 3: 0 1 1
----------
1 1 1 โ 7
๐ฃ โAnyone says YES? Then YES!โ
๐ 3. Bitwise XOR (^
) โ โOnly if different!โ
Rule: Give 1 only if they are different.
5: 1 0 1
^ 3: 0 1 1
----------
1 1 0 โ 6
๐ฃ โSame = 0, Different = 1!โ
๐งจ 4. Bitwise NOT (~
) โ โFlip it!โ
Rule: Turn all 1s to 0s, and 0s to 1s.
print(~5) #-6
Rule
~n = -(n + 1)
โฉ 5. Left Shift (<<
) โ โPush blocks to the left!โ
5 = 1 0 1
5 << 1 โ 1 0 1 0 โ 10
๐ฃ โAdd 0 at the end โ like making it 2ร bigger!โ
โช 6. Right Shift (>>
) โ โPush blocks to the right!โ
5 = 1 0 1
5 >> 1 โ 0 1 0 โ 2
๐ฃ โMove to the right โ makes it smaller (like divide by 2)!
Leave a Reply