Chapter 30: Bitwise

Bitwise operators.

Many beginners skip or fear bitwise operations because they look “low-level” or “math-y”, but in real Go code they appear surprisingly often — especially when you work with:

  • flags / permissions
  • network protocols
  • file modes
  • colors (RGB)
  • crypto / hashing
  • compression
  • performance-critical code
  • embedded / systems programming

Go has very clean and complete bitwise operators — actually one more than most C-family languages (&^ bit clear).

Let’s go through them slowly, like a patient teacher would do it in a live session — theory + visual binary examples + runnable code + common real-world patterns.

1. The Six Bitwise Operators in Go

Operator Name What it does (bit by bit) Example (x = 10 = 1010₂, y = 12 = 1100₂) Result (binary) Decimal result Most common use
& AND 1 only if both bits are 1 x & y 1000 8 Mask / keep bits
OR 1 if at least one bit is 1 x y 1110
^ XOR 1 if bits are different x ^ y 0110 6 Toggle / difference
&^ AND NOT (bit clear) Clear bits where right operand has 1 (Go-specific) x &^ y 0010 2 Remove flags
<< Left shift Shift bits left, fill with 0 on right x << 2 101000 40 Multiply by powers of 2
>> Right shift Shift bits right, preserve sign (arithmetic shift) y >> 1 0110 6 Divide by powers of 2

2. Visual Understanding (Binary Table)

Let’s take two 8-bit numbers for clarity:

text
Operation Binary result Decimal Explanation
x & y 00001000 8 only positions where both 1 → bit 3
x y 00001110 14
x ^ y 00000110 6 positions where exactly one has 1
x &^ y 00000010 2 x with all 1-bits from y cleared
x << 2 00101000 40 shifted left 2 positions
y >> 1 00000110 6 shifted right 1 position

3. Runnable Examples — Copy-Paste & Run

Create bitwise_operators.go:

Go

4. Real-World Patterns You Will Actually Use

Pattern 1: Bit flags / permissions (most common use)

Go

Pattern 2: Colors (RGB)

Go

Pattern 3: Fast multiply / divide by powers of 2

Go

5. Common Beginner Mistakes

  1. Forgetting that << and >> have higher precedence than +/-
Go
  1. Shifting negative numbers right → sign bit preserved
Go
  1. Using ^ thinking it’s NOT (it’s XOR)
Go

6. Quick Practice – Try These

Predict the result (in decimal):

  1. 13 & 6 (1101 & 0110)
  2. 13 | 6
  3. 13 ^ 6
  4. 13 &^ 6
  5. 7 << 2
  6. 28 >> 2

Run them — which one surprised you most?

Any part still unclear?

  • How &^ is different from & ~ in other languages?
  • Bitwise tricks for checking if power of 2?
  • When to prefer bit flags vs bool fields in structs?
  • Or ready for pointer operators (& and *) next?

Keep playing with small numbers in binary — once you start seeing the bits, bitwise becomes intuitive and powerful.

You’re doing excellent work — keep asking! 💪🇮🇳🚀

You may also like...

Leave a Reply

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