Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. bytes
8 min read

Bytes & Encoding

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.

str versus bytes

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:

python
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:

python
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:

python
1>>> "a" + b"a"
2Traceback (most recent call last):
3  File "<stdin>", line 1, in <

Encoding and Decoding

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:

python
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:

python
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:

python
1b"\xffabc".decode(errors="replace")    # Return: '�abc'
2b"\xff\xfe".decode("latin-1")          # Return: 'ÿþ'
Stay in bytes
In exploit scripts, do everything in 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.

bytearray

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:

python
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.

Hex and Base64

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:

python
1b"flag".hex()                 # Return: '666c6167'
2b"flag".hex(" ")              # Return: '66 6c 61 67'
3bytes.fromhex

Base64 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:

python
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:

  • Hex uses only 0–9 and a–f, and has an even length.
  • Base64 uses 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().
Info
Encodings are not encryption. Hex and Base64 hide nothing; they only change how bytes are written down. If a challenge gives you a Base64 blob, decoding it is the first step, not the solution.

Packing Integers

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:

python
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.

struct

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:

python
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:

CodeMeaning
<Little-endian
>Big-endian
BUnsigned 8-bit integer (1 byte)
HUnsigned 16-bit integer (2 bytes)
IUnsigned 32-bit integer (4 bytes)
QUnsigned 64-bit integer (8 bytes)
b, h, i, qThe signed versions of the above
4sA 4-byte bytes string
xOne padding byte, skipped
Always give a byte order
Without < 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:

python
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.

XOR and Bitwise Operations

Python's bitwise operators work on integers of any size:

OperatorNameExampleResult
&AND0b1100 & 0b10108 (0b1000)
|OR0b1100 | 0b101014 (0b1110)
^XOR0b1100 ^ 0b10106 (0b0110)
~NOT~5-6
<<Left shift1 << 416
>>Right shift0x1234 >> 818 (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:

python
1data = b"hello"
2key = b"\x01\x02\x03\x04\x05"
3bytes(a ^ b for a, b in zip(data, key

When the key is shorter than the data, repeat it with itertools.cycle, covered in Functools & Itertools:

python
1from itertools import cycle
2
3ct = bytes(a ^ b for a, b in zip(b"attack at dawn", cycle(

Breaking Single-Byte XOR

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:

3c363b3d21226a28056b2905332e29056a2d34056b342c6928293f27

We 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:

python
1ct = bytes.fromhex("3c363b3d21226a28056b2905332e29056a2d34056b342c6928293f27")
2
3for key in range(256):
4
0x5a 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.

module
>
4TypeError: can only concatenate str (not "bytes") to str
<
module
>
4UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
4bytes(buf) # Return: b'BAAACC'
(
"666c6167"
)
# Return: b'flag'
)
# Return: b'\xde\xad\xbe\xef'
3hex(int.from_bytes(b"\xef\xbe\xad\xde", "little")) # Return: '0xdeadbeef'
,
0x401136
)
# Return: b'6\x11@\x00\x00\x00\x00\x00'
5struct.pack(">H", 8080) # Return: b'\x1f\x90'
6struct.unpack("<IH", b"\x01\x00\x00\x00\x02\x00") # Return: (1, 2)
e_version
=
struct
.
unpack
(
"<4sBBB9xHHI"
,
header
)
4magic # Return: b'\x7fELF'
5cls # Return: 2, meaning 64-bit
6e_machine # Return: 62, meaning x86-64
)
)
# Return: b'igohj'
b"key"
)
)
)
4bytes(a ^ b for a, b in zip(ct, cycle(b"key"))) # Return: b'attack at dawn'
pt
=
bytes
(
b
^
key
for
b
in
ct
)
5 if pt.startswith(b"flag{"):
6 print(hex(key), pt)