Bits, Bytes & Byte Order
Before we build real frames and packets, we need a few tools for working with binary data. Network protocols pack numbers, flags and addresses tightly into bytes, and you will read them in binary, hexadecimal and decimal all the time.
Three ways to write a number
| Base | Digits | Prefix in Python | Example (decimal 172) |
|---|---|---|---|
| Decimal | 0–9 | none | 172 |
| Binary | 0–1 | 0b |
0b10101100 |
| Hexadecimal | 0–9, a–f | 0x |
0xac |
One hex digit is exactly 4 bits (a nibble), so one byte is always two hex digits. That's why hex is everywhere in networking: MAC addresses, IPv6 addresses and packet dumps.
n = 172
print(bin(n), hex(n), n)
print(f"{n:08b} {n:02x} {n:d}")
print(int("10101100", 2), int("ac", 16), 0b1010_1100, 0xAC)
for octet in [0, 1, 127, 128, 192, 255]:
print(f"{octet:>3} = {octet:08b} = 0x{octet:02x}")0b10101100 0xac 172
10101100 ac 172
172 172 172 172
0 = 00000000 = 0x00
1 = 00000001 = 0x01
127 = 01111111 = 0x7f
128 = 10000000 = 0x80
192 = 11000000 = 0xc0
255 = 11111111 = 0xff
Bitwise operations
Network code constantly sets, clears and tests individual bits: TCP flags, subnet masks, IP header fields that share a byte.
| Operator | Name | Typical use |
|---|---|---|
a & b |
AND | keep only some bits (apply a mask) |
a | b |
OR | turn bits on (set a flag) |
a ^ b |
XOR | flip bits, checksums |
~a |
NOT | invert (in Python, combine with a mask: ~a & 0xff) |
a << n, a >> n |
shifts | move a field into or out of position |
The first byte of every IPv4 header holds two 4-bit fields: the version (4) and the header length in 32-bit words (5). Packing and unpacking them is a typical job for shifts and masks:
version, ihl = 4, 5
first_byte = (version << 4) | ihl
print(f"packed: 0x{first_byte:02x} = {first_byte:08b}")
print("version:", first_byte >> 4)
print("ihl: ", first_byte & 0x0F, "words =", (first_byte & 0x0F) * 4, "bytes")
# TCP flags live in single bits
FIN, SYN, RST, PSH, ACK = 0x01, 0x02, 0x04, 0x08, 0x10
flags = SYN | ACK
print(f"flags=0x{flags:02x} SYN set: {bool(flags & SYN)} FIN set: {bool(flags & FIN)}")
flags &= ~SYN & 0xFF # clear SYN
print(f"after clearing SYN: 0x{flags:02x}")packed: 0x45 = 01000101
version: 4
ihl: 5 words = 20 bytes
flags=0x12 SYN set: True FIN set: False
after clearing SYN: 0x10
bytes and bytearray
Python's bytes type is an immutable sequence of integers 0–255; bytearray is the mutable version. Indexing a bytes gives an int, slicing gives bytes.
data = bytes([0x45, 0x00, 0x00, 0x3c])
print(data, len(data))
print(data[0], data[1:3])
print(data.hex(), data.hex(" "))
print(bytes.fromhex("de ad be ef"))
buf = bytearray(4)
buf[0] = 0x45
buf[3] = 60
print(buf.hex(" "))b'E\x00\x00<' 4
69 b'\x00\x00'
4500003c 45 00 00 3c
b'\xde\xad\xbe\xef'
45 00 00 3c
Byte order (endianness)
A 16-bit or 32-bit number occupies several bytes. In which order are they stored? There are two conventions:
- Big-endian: most significant byte first.
0x1234is stored as12 34. - Little-endian: least significant byte first:
34 12. This is what x86 and ARM CPUs use in memory.
Internet protocols always use big-endian, which is therefore also called network byte order. Forgetting to convert is one of the most common bugs in network code: port 80 (0x0050) sent little-endian arrives as port 20480 (0x5000).
port = 80
big = port.to_bytes(2, "big")
little = port.to_bytes(2, "little")
print("big-endian: ", big.hex(" "))
print("little-endian:", little.hex(" "))
print("misread:", int.from_bytes(little, "big"))big-endian: 00 50
little-endian: 50 00
misread: 20480
The struct module
For whole headers, the struct module packs and unpacks several fields at once using a format string. The first character ! means network byte order (big-endian, no padding).
| Code | C type | Size |
|---|---|---|
B |
unsigned char | 1 byte |
H |
unsigned short | 2 bytes |
I |
unsigned int | 4 bytes |
Q |
unsigned long long | 8 bytes |
4s, 6s |
bytes of that length | n bytes |
x |
pad byte | 1 byte |
import struct
# A UDP header: source port, destination port, length, checksum (4 x 16 bits)
header = struct.pack("!HHHH", 51514, 53, 40, 0)
print(header.hex(" "), len(header), "bytes")
print(struct.unpack("!HHHH", header))
print(struct.calcsize("!BBHI6s"))
# Without '!' Python uses the machine's native order (little-endian here)
print(struct.pack("<H", 53).hex(), struct.pack("!H", 53).hex())c9 3a 00 35 00 28 00 00 8 bytes
(51514, 53, 40, 0)
14
3500 0035
Tip: Always use
!(or>) in network formats. The native@default adds alignment padding and uses the CPU's byte order, so it will silently produce wrong headers.
Test yourself
What is 0xC0 in decimal?
- 12
- 160
- 192
- 208
Which byte order do Internet protocol headers use?
- Little-endian
- Big-endian (network byte order)
- Whatever the sender's CPU uses
- Middle-endian
Which struct format packs a 16-bit and then a 32-bit unsigned integer in network byte order?
- "HI"
- "!HI"
- "<HI"
- "!IH"