String#unpack
str.unpack(template) -> array | str.unpack1(template) -> value Returns:
Array (unpack) or Object (unpack1) · Updated March 13, 2026 · String Methods strings binary encoding parsing
The unpack method decodes a binary string (such as one created by pack) according to a template format string. It returns an array of values extracted from the binary data. The unpack1 method works identically but returns only the first value instead of an array—useful when you know the template will produce exactly one result.
Syntax
str.unpack(template)
str.unpack1(template)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
template | String | — | A format string specifying how to decode the binary data. Each character represents a directive for decoding. |
Common Template Directives
| Directive | Meaning |
|---|---|
C | Unsigned 8-bit integer |
S | Unsigned 16-bit integer (little-endian) |
L | Unsigned 32-bit integer (little-endian) |
s | Signed 16-bit integer |
l | Signed 32-bit integer |
f | Float (single precision) |
d | Double precision float |
A | ASCII string (trailing nulls and spaces stripped) |
a | ASCII string (preserves trailing characters) |
H | Hex string (high nibble first) |
h | Hex string (low nibble first) |
B | Bit string (most significant bit first) |
b | Bit string (least significant bit first) |
x | Null byte |
@ | Null fill to absolute position |
Prefixes: < = little-endian, > = big-endian, N = network byte order (big-endian).
Examples
Basic integer unpacking
# Pack integers into binary, then unpack
binary = [255, 0, 16, 0].pack('C*')
# => "\xFF\x00\x10\x00"
binary.unpack('C*')
# => [255, 0, 16, 0]
binary.unpack1('C')
# => 255
Unpacking a network packet header
# Simulate a 4-byte header: version(1 byte) + type(1 byte) + length(2 bytes)
packet = "\x04\x01\x00\x50" # version=4, type=1, length=80
packet.unpack('CCn')
# => [4, 1, 80]
# Using unpack1 for single values
packet.unpack1('C')
# => 4
# Big-endian 16-bit integer
packet.unpack('C2n')
# => [4, 1, 80]
Working with binary structs
# Unpack a timestamp (seconds + milliseconds)
binary = [1700000000, 500].pack('L L')
# => ">\xF5F\x00\x00\x01\xf4"
binary.unpack('L2')
# => [1700000000, 500]
# Using unpack1 for the first component
binary.unpack1('L')
# => 1700000000
Hex string decoding
hex_string = "48656c6c6f" # "Hello" in hex
hex_string.unpack('H*')
# => ["48656c6c6f"]
# Decode pairs of hex digits
hex_string.unpack('H2' * 5)
# => ["48", "65", "6c", "6c", "6f"]
hex_string.pack('H*').unpack('C*')
# => [72, 101, 108, 108, 111]
Common Patterns
Network protocol parsing: Unpack binary protocols byte-by-byte using C directives.
Binary file reading: Read file contents and unpack structured data like headers.
Data serialization: Use pack/unpack for efficient binary serialization without overhead of JSON/YAML.
Bit-level manipulation: Extract individual bits with B or b directives.