Binary and Hexadecimal

Computers store everything as binary (base 2). Hexadecimal (base 16) is a human-friendly shorthand for binary. Understanding these systems is essential for working with memory, networking, and low-level code.

Why It Matters

IP addresses, MAC addresses, colors in CSS, memory addresses, file permissions — all use binary or hex under the hood. If you can’t read 0xFF or 0b1010, you’ll struggle with debugging and systems work.

Binary (Base 2)

Each digit (bit) is either 0 or 1. Place values are powers of 2.

Binary:   1    0    1    1
Place:    2^3  2^2  2^1  2^0
Value:    8  + 0  + 2  + 1  = 11 (decimal)

Hexadecimal (Base 16)

Digits: 0-9 then A-F (A=10, B=11, …, F=15). Each hex digit maps to exactly 4 bits.

Hex:  0x2F
  2 = 0010
  F = 1111
Binary: 00101111 = 47 (decimal)

Conversion Table

DecimalBinaryHex
000000
501015
101010A
151111F
161000010
25511111111FF

Code Example

# Python has built-in conversion
n = 42
print(bin(n))   # '0b101010'
print(hex(n))   # '0x2a'
print(oct(n))   # '0o52'
 
# Parse from string
print(int('101010', 2))   # 42  (binary to decimal)
print(int('2a', 16))      # 42  (hex to decimal)
 
# Bitwise operations
a = 0b1100  # 12
b = 0b1010  # 10
print(bin(a & b))   # 0b1000  (AND = 8)
print(bin(a | b))   # 0b1110  (OR  = 14)
print(bin(a ^ b))   # 0b0110  (XOR = 6)
print(bin(~a & 0xF)) # 0b0011 (NOT, masked to 4 bits = 3)

Where You’ll See This

  • Memory addresses: 0x7ffeefbff8a0
  • CSS colors: #2563eb = R:37 G:99 B:235
  • File permissions: chmod 755 = rwxr-xr-x = 111 101 101 in binary
  • Network masks: 255.255.255.0 = 0xFFFFFF00