Lesson 1 of 7

Bits, Bytes & Binary

Everything a computer stores, from numbers to text to images, is made of bits that are either 0 or 1. You'll learn , hexadecimal and how negative numbers and text are represented.

A bit is a single 0 or 1. Eight bits make a byte, which can represent 256 different values (2^8). Binary is just place-value counting with 2s instead of 10s: the binary number 1011 means 1×8 + 0×4 + 1×2 + 1×1 = 11. Hexadecimal (base 16, digits 0-9 then a-f) is shorthand — one hex digit is exactly four bits, so 0xFF is 11111111 is 255.

# Explore binary in any language — Python shown:
print(bin(11))       # 0b1011
print(0b1011)        # 11
print(hex(255))      # 0xff
print(0xff)          # 255

# Bitwise operators work directly on the bits:
a, b = 0b1100, 0b1010
print(bin(a & b))    # 0b1000  AND — both bits set
print(bin(a | b))    # 0b1110  OR  — either bit set
print(bin(a ^ b))    # 0b0110  XOR — exactly one set
print(bin(a << 1))   # 0b11000 shift left = ×2
print(bin(a >> 2))   # 0b11    shift right = ÷4
Python (loads on first run)Ctrl+Enter runs

Negative numbers use two's complement: to negate, flip every bit and add one. The top bit acts as the sign. This is why an 8-bit signed integer ranges from -128 to 127, and why integer overflow wraps around to a huge negative number — the bits just carried past the sign position.

Text
8-bit two's complement:
  0000 0101  =  5
  1111 1011  = -5   (flip all bits of 5, add 1)
  0111 1111  =  127 (biggest positive)
  1000 0000  = -128 (most negative)
  0111 1111 + 1 = 1000 0000   -> 127 + 1 = -128. Overflow!

Text is numbers too (ASCII/Unicode):
  'A' = 65 = 0100 0001
  'a' = 97 = 0110 0001   (one bit apart — that's why
                          case-toggling is a single XOR)
Finished reading?Mark it done to track your progress.

Tip: use the ← and → keys to move between lessons.