Codectionary / Developer documentation / Ruby

Binary Packing and Byte Order

Array#pack encodes values into a binary string and String#unpack reverses the process. Directives define field width, signedness and byte order. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

values.pack("nC"); bytes.unpack("nC")

Examples

Binary Packing and Byte Order

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

packet = [513, 7].pack("nC")
p packet.bytes
p packet.unpack("nC")
  1. Expected output: [2, 1, 7] [513, 7]
  2. n writes an unsigned 16-bit big-endian value: 513 is bytes 2 and 1. C writes the final unsigned byte.

Best practices

  • Specify byte order explicitly for portable binary formats.
  • Validate numeric ranges and packet length before interpreting untrusted binary data.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading