pack / unpack

pack(string $format, mixed ...$values): string — unpack(string $format, string $data, int $offset = 0): array

Binary data packing and unpacking: format letters pin both type and byte order (n/N big-endian, v/V little-endian, d/f floats, a/A strings) - the low-level tool for wire protocols and binary files.

C C23

C23
#include <stdint.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    /* shift and mask: C has no built-in byte-order helpers */
    uint16_t n = 258;
    uint8_t b1[2] = {(uint8_t)(n >> 8), (uint8_t)n}; /* big-endian = network byte order (pack "n") */
    uint32_t v = 0x01020304u;
    uint8_t b2[4] = {(uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24)}; /* little-endian (pack "V") */
    printf("%02x%02x\n", b1[0], b1[1]);
    printf("%02x%02x%02x%02x\n", b2[0], b2[1], b2[2], b2[3]);
    printf("%u\n", ((unsigned)b1[0] << 8) | b1[1]); /* unpack big-endian u16 */
    /* unpack "d": raw bytes -> double needs memcpy (only the bit pattern matters) */
    uint8_t le[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x3f}; /* IEEE-754 LE bit pattern of 1.5 */
    double d;
    memcpy(&d, le, sizeof d);
    printf("%.1f\n", d);
    return 0;
}
Output
0102
04030201
258
1.5

C++ C++26

C++26
#include <cstdint>
#include <cstdio>
#include <cstring>

int main() {
    // shift and mask: the portable core under every byte-order helper
    std::uint16_t n = 258;
    std::uint8_t b1[2] = {(std::uint8_t)(n >> 8), (std::uint8_t)n}; // big-endian = network byte order (pack "n")
    std::uint32_t v = 0x01020304u;
    std::uint8_t b2[4] = {(std::uint8_t)v, (std::uint8_t)(v >> 8), (std::uint8_t)(v >> 16), (std::uint8_t)(v >> 24)}; // little-endian (pack "V")
    std::printf("%02x%02x\n", b1[0], b1[1]);
    std::printf("%02x%02x%02x%02x\n", b2[0], b2[1], b2[2], b2[3]);
    std::printf("%u\n", ((unsigned)b1[0] << 8) | b1[1]); // unpack big-endian u16
    // unpack "d": raw bytes -> double needs memcpy (only the bit pattern matters)
    std::uint8_t le[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x3f}; // IEEE-754 LE bit pattern of 1.5
    double d;
    std::memcpy(&d, le, sizeof d);
    std::printf("%.1f\n", d);
}
Output
0102
04030201
258
1.5

C# v11.0.100

v11.0.100
// BitConverter follows host byte order: build both layouts explicitly to stay deterministic
ushort n = 258;
uint v = 0x01020304u;
byte[] b1 = { (byte)(n >> 8), (byte)n }; // big-endian = network byte order (pack "n")
byte[] b2 = { (byte)v, (byte)(v >> 8), (byte)(v >> 16), (byte)(v >> 24) }; // little-endian (pack "V")
Console.WriteLine(Convert.ToHexString(b1).ToLowerInvariant());
Console.WriteLine(Convert.ToHexString(b2).ToLowerInvariant());
Console.WriteLine((b1[0] << 8) | b1[1]); // unpack big-endian u16
Output
0102
04030201
258

Go v1.27.4

v1.27.4
package main

import (
	"encoding/binary"
	"encoding/hex"
	"fmt"
)

func main() {
	b1 := make([]byte, 2)
	binary.BigEndian.PutUint16(b1, 258) // big-endian = network byte order (pack "n")
	b2 := make([]byte, 4)
	binary.LittleEndian.PutUint32(b2, 0x01020304) // little-endian (pack "V")
	fmt.Println(hex.EncodeToString(b1))
	fmt.Println(hex.EncodeToString(b2))
	fmt.Println(binary.BigEndian.Uint16([]byte{0x01, 0x02})) // unpack big-endian u16
}
Output
0102
04030201
258

Java v27.0.1

v27.0.1
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class Main {
    static String hex(byte[] a) {
        StringBuilder sb = new StringBuilder();
        for (byte b : a) sb.append(String.format("%02x", b));
        return sb.toString();
    }

    public static void main(String[] args) {
        // ByteBuffer is big-endian by default, matching network byte order (pack "n")
        ByteBuffer be = ByteBuffer.allocate(2);
        be.putShort((short) 258);
        // order() switches the layout for little-endian (pack "V")
        ByteBuffer le = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
        le.putInt(0x01020304);
        System.out.println(hex(be.array()));
        System.out.println(hex(le.array()));
        System.out.println(ByteBuffer.wrap(new byte[] {0x01, 0x02}).getShort() & 0xffff); // unpack big-endian u16
    }
}
Output
0102
04030201
258

JavaScript v26.13.1

v26.13.1
// Buffer is Node's byte array; the BE/LE write methods make byte order explicit
const be = Buffer.alloc(2);
be.writeUInt16BE(258); // big-endian = network byte order (pack "n")
const le = Buffer.alloc(4);
le.writeUInt32LE(0x01020304); // little-endian (pack "V")
console.log(be.toString("hex"));
console.log(le.toString("hex"));
console.log(be.readUInt16BE(0)); // unpack big-endian u16 back to int
Output
0102
04030201
258

PHP v8.6.0

v8.6.0
// format letters pin type AND byte order: n = u16 big-endian (network), V = u32 little-endian
echo bin2hex(pack("n", 258)), PHP_EOL;        // 258 = 0x0102
echo bin2hex(pack("V", 0x01020304)), PHP_EOL; // little-endian bytes
echo unpack("nnum", pack("n", 258))["num"], PHP_EOL; // unpack: name the key before the letter
Output
0102
04030201
258

Python v3.15.2

v3.15.2
import struct

# > = big-endian (network byte order), < = little-endian - the exact n/V twins
print(struct.pack(">H", 258).hex())
print(struct.pack("<I", 0x01020304).hex())
print(struct.unpack(">H", bytes([0x01, 0x02]))[0])  # unpack big-endian u16
Output
0102
04030201
258

Rust v1.99.1

v1.99.1
fn main() {
    // std has no byte-order helpers: shift and mask, exactly like the C version
    let n: u16 = 258;
    let b1 = [(n >> 8) as u8, n as u8]; // big-endian = network byte order (pack "n")
    let v: u32 = 0x01020304;
    let b2 = [v as u8, (v >> 8) as u8, (v >> 16) as u8, (v >> 24) as u8]; // little-endian (pack "V")
    println!("{}", b1.iter().map(|b| format!("{:02x}", b)).collect::<String>());
    println!("{}", b2.iter().map(|b| format!("{:02x}", b)).collect::<String>());
    println!("{}", u16::from_be_bytes([0x01, 0x02])); // unpack big-endian u16
}
Output
0102
04030201
258

TypeScript v26.13.1

v26.13.1
// Buffer is Node's byte array; the BE/LE write methods make byte order explicit
const be: Buffer = Buffer.alloc(2);
be.writeUInt16BE(258); // big-endian = network byte order (pack "n")
const le: Buffer = Buffer.alloc(4);
le.writeUInt32LE(0x01020304); // little-endian (pack "V")
console.log(be.toString("hex"));
console.log(le.toString("hex"));
console.log(be.readUInt16BE(0)); // unpack big-endian u16 back to int
Output
0102
04030201
258

Language differences

C: no built-in packing functions - shift and mask by hand; memcpy only ferries raw bytes <-> float bit patterns (the example's last line). Real code writes explicit-endian loops or pulls a serialization library.

C++: same hand-rolled shifts as C; production code uses std::memcpy + fixed-endian loops or Boost.Endian's endian_buffer.

C#: BinaryWriter writes in host byte order (little-endian on x86/arm64) - cross-endian work builds bytes explicitly (the example); BitConverter.IsLittleEndian probes the host order and IPAddress.HostToNetworkOrder converts a single value to network order.

Go: encoding/binary's BigEndian/LittleEndian are the direct pack/unpack counterparts; binary.Size gives a fixed-size type's byte count.

Java: ByteBuffer defaults to big-endian (network byte order) and order(ByteOrder.LITTLE_ENDIAN) switches - a 1:1 match for pack's n/V.

JavaScript: Node's Buffer offers the writeUInt16BE/LE family; in browsers use DataView whose setUint16 second parameter picks the order.

PHP: pack/unpack use a format-letter table - n = u16 big-endian, N = u32 big-endian, v = u16 little-endian, V = u32 little-endian (mnemonic: n/N stay big, v/V are little), d = double, f = float, a/A = padded strings, x/X/@ = pad/backtrack/absolute offset; unpack names its keys BEFORE the letter (e.g. 'nnum'); * repeats to the end of the data.

Python: struct is the native counterpart - the format prefix >/</! (network)/= (native) picks the byte order, and pack/unpack/calcsize map 1:1.

Rust: std has no byte-order helpers - shift by hand; production code uses the byteorder crate's WriteBytesExt/ReadBytesExt or the built-in to_be_bytes/from_le_bytes family.

TypeScript: same as JavaScript - DataView in browsers, Buffer with type declarations in Node.