Bitwise Operators

๐Ÿง  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 1
  • 3 = ๐Ÿงฑ 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 &lt;&lt; 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)!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *