A str holds text; a bytes holds raw octets, values from 0 to 255. The difference is invisible until you read a binary file, talk to a network socket, or write an exploit, and then it's the source of most bugs. Security work in Python lives on the bytes side: shellcode, packed addresses, file headers and ciphertext are all bytes, not text. This lesson covers moving between the two, and the encodings you'll meet constantly: hex, Base64, and packed integers.
A bytes literal looks like a string with a b in front. Printable ASCII characters show as themselves, and everything else shows as a \x escape with two hex digits:
1b"flag" # 4 bytes: 0x66 0x6c 0x61 0x67
2b"\x7fELF\x02\x01" # the first bytes of an ELF file
3bytes([72, 105]) # Return: b'Hi'bytes behaves like a sequence, with one surprise: indexing gives an int, not a one-character bytes. Slicing still gives bytes:
1data = b"Hi"
2data[0] # Return: 72
3data[:1] # Return: b'H'Python keeps str and bytes strictly apart. Mixing them is a TypeError, not a silent conversion:
1>>> "a" + b"a"
2Traceback (most recent call last):
3 File "<stdin>", line 1, in <To go from text to bytes, you encode the string, and to go back you decode the bytes. An encoding is the rule for turning characters into bytes. The one you'll almost always use is UTF-8, which is the default for both methods:
1"café".encode() # Return: b'caf\xc3\xa9'
2b"caf\xc3\xa9".decode() # Return: 'café'UTF-8 stores ASCII characters as a single byte each, but other characters take two to four bytes. That's why len("é") is 1 while len("é".encode()) is 2.
Not every sequence of bytes is valid UTF-8, and decoding invalid bytes raises an error:
1>>> b"\xff".decode()
2Traceback (most recent call last):
3 File "<stdin>", line 1, in When you're handed bytes that aren't really text, such as program output that might contain binary data, you have two ways out. errors="replace" swaps undecodable bytes for �, and the Latin-1 encoding maps every byte 0–255 to exactly one character, so it never fails and round-trips perfectly:
1b"\xffabc".decode(errors="replace") # Return: '�abc'
2b"\xff\xfe".decode("latin-1") # Return: 'ÿþ'bytes from start to finish: b"A" * 40 + address, not a string you encode at the end. Encoding a string with UTF-8 turns any character above \x7f into two bytes, which silently corrupts addresses and shellcode.bytes is immutable, like str. Its mutable counterpart is bytearray, which supports item assignment and in-place appending. Use it to patch bytes or build a buffer piece by piece:
1buf = bytearray(b"AAAA")
2buf[0] = 0x42 # bytearray(b'BAAA')
3buf += b"CC" # bytearray(b'BAAACC')Patching a binary is a common use: read the file into a bytearray, change the bytes at an offset, and write it back out.
Raw bytes don't print well, so they're often passed around encoded as text. Two encodings dominate.
Hex writes each byte as two hexadecimal digits. bytes.hex() and bytes.fromhex() convert in each direction, and hex() can take a separator:
1b"flag".hex() # Return: '666c6167'
2b"flag".hex(" ") # Return: '66 6c 61 67'
3bytes.fromhexBase64 packs every 3 bytes into 4 printable characters, so binary data can travel through anything that expects text, such as email, JSON or a URL. The base64 module handles it, and both functions return bytes:
1import base64
2
3base64.b64encode(b"flag{b64}") # Return: b'ZmxhZ3tiNjR9'
4base64.b64decode("ZmxhZ3tiNjR9") # Return: b'flag{b64}'Recognizing each encoding on sight saves a lot of time in challenges:
0–9 and a–f, and has an even length.A–Z, a–z, 0–9, + and /. Its length is a multiple of 4, and it often ends in one or two = padding characters. A variant for URLs swaps + and / for - and _; decode it with base64.urlsafe_b64decode().A number inside a program is stored as a fixed number of bytes: 4 for a 32-bit integer, 8 for a 64-bit pointer. Turning a Python int into those bytes is called packing, and the reverse is unpacking.
The order of those bytes is the byte order, or endianness. Little-endian stores the least significant byte first, and it's what x86 and most ARM systems use. Big-endian stores the most significant byte first, and it's the standard for network protocols. The same number looks reversed between the two:
1(0xdeadbeef).to_bytes(4, "little") # Return: b'\xef\xbe\xad\xde'
2(0xdeadbeef).to_bytes(4, "big"int.to_bytes() and int.from_bytes() take the number of bytes and the byte order. They're fine for a single value.
For a fixed layout of several fields, such as a file header or a network packet, the struct module is the better tool. struct.pack() takes a format string describing the layout, and the values to pack. struct.unpack() takes the format and the bytes, and always returns a tuple:
1import struct
2
3struct.pack("<I", 0xdeadbeef) # Return: b'\xef\xbe\xad\xde'
4struct.pack("<Q"The first character of the format sets the byte order, and each letter after it is one field:
| Code | Meaning |
|---|---|
< | Little-endian |
> | Big-endian |
B | Unsigned 8-bit integer (1 byte) |
H | Unsigned 16-bit integer (2 bytes) |
I | Unsigned 32-bit integer (4 bytes) |
Q | Unsigned 64-bit integer (8 bytes) |
b, h, i, q | The signed versions of the above |
4s | A 4-byte bytes string |
x | One padding byte, skipped |
< or >, struct uses your machine's native byte order and also inserts alignment padding between fields, the way a C compiler lays out a struct. struct.calcsize("BI") is 8 on x86-64, while struct.calcsize("<BI") is 5. Start every format with < or > so the layout is exactly what you wrote.Here's struct parsing the start of a 64-bit ELF header, the same fields the ELF parser project reads in C. The format reads the 4-byte magic, three single-byte fields, skips 9 bytes of padding, then reads two 16-bit fields and a 32-bit one:
1header = bytes.fromhex("7f454c4602010100000000000000000002003e0001000000")
2
3magic, cls, data, version, e_type, e_machine,When writing exploits, pwntools wraps the most common cases in short helpers: p64(addr) is struct.pack("<Q", addr), and u64(data) unpacks it again.
Python's bitwise operators work on integers of any size:
| Operator | Name | Example | Result |
|---|---|---|---|
& | AND | 0b1100 & 0b1010 | 8 (0b1000) |
| | OR | 0b1100 | 0b1010 | 14 (0b1110) |
^ | XOR | 0b1100 ^ 0b1010 | 6 (0b0110) |
~ | NOT | ~5 | -6 |
<< | Left shift | 1 << 4 | 16 |
>> | Right shift | 0x1234 >> 8 | 18 (0x12) |
Masking with & keeps only the bits you want: 0x1234 & 0xff is 0x34, the lowest byte. Because Python integers have no fixed width, ~5 is -6 rather than 0xfffffffa; mask the result, as in ~5 & 0xffffffff, when you need C's 32-bit behavior.
XOR is the workhorse of simple encryption, because it undoes itself: (a ^ k) ^ k == a. Applying the same key twice gets the original back. There's no XOR operator for bytes objects, so XOR them byte by byte with zip and a comprehension:
1data = b"hello"
2key = b"\x01\x02\x03\x04\x05"
3bytes(a ^ b for a, b in zip(data, keyWhen the key is shorter than the data, repeat it with itertools.cycle, covered in Functools & Itertools:
1from itertools import cycle
2
3ct = bytes(a ^ b for a, b in zip(b"attack at dawn", cycle(If a message was XORed with a single repeating byte, there are only 256 possible keys, so you can try them all. Here's some ciphertext, given in hex the way a challenge would hand it to you:
3c363b3d21226a28056b2905332e29056a2d34056b342c6928293f27We know the flag format starts with flag{, so we decode the hex, XOR with every possible key, and keep the result that starts with it:
1ct = bytes.fromhex("3c363b3d21226a28056b2905332e29056a2d34056b342c6928293f27")
2
3for key in range(256):
40x5a b'flag{x0r_1s_its_0wn_1nv3rse}'When you don't know any of the plaintext, score each candidate instead, for example by counting how many of its bytes are printable letters and spaces, and keep the highest-scoring one.