Bytes and binary data

suggest change

In Ruby, binary data is represented using standard String instances configured with the binary encoding (Encoding::ASCII_8BIT, also aliased as Encoding::BINARY). This approach allows binary buffers to leverage Ruby's string manipulation methods while avoiding character-encoding errors or invalid Unicode transformations.


1. Creating and Flagging Binary Strings

The .b Method

The fastest and most idiomatic way to produce a binary string from a regular string is the .b method:

text = "café"
binary = text.b

puts binary.encoding # => ASCII-8BIT
puts binary.bytesize # => 5 (c, a, f, and 2 bytes for é in UTF-8)

Specifying Encoding Explicitly

You can also initialize a string with Encoding::BINARY or force its encoding without converting the underlying bytes:

# Direct initialization
raw = String.new("data\x00\x01\xFF", encoding: Encoding::BINARY)

# Force existing string to binary without mutating bytes
str = "hello"
str.force_encoding(Encoding::BINARY)

2. Inspecting Bytes: bytes, bytesize, and getbyte

bytesize vs length

For UTF-8 strings, .length returns the number of characters, while .bytesize returns the raw byte length:

str = "🚀 rocket"
puts str.length   # => 8 (1 emoji + 1 space + 6 letters)
puts str.bytesize # => 11 (4 bytes for emoji + 1 + 6)

Accessing Individual Bytes

data = "Ruby".b

# Array of byte integers (0..255)
p data.bytes # => [82, 117, 98, 121]

# Iterate through each byte
data.each_byte do |byte|
  puts "#{byte} (0x#{byte.to_s(16).upcase})"
end

# Read and mutate single byte values
puts data.getbyte(0) # => 82 ('R')

data.setbyte(0, 114) # Replace 'R' with 'r' (ASCII 114)
puts data            # => "ruby"

3. Packing Data into Binary (Array#pack)

Array#pack formats arrays of numbers and strings into packed binary strings using directive templates:

# Pack an unsigned 16-bit big-endian integer (n) and 32-bit big-endian integer (N)
packed = [1024, 70_000].pack('nN')

p packed.bytes
# => [4, 0, 0, 1, 17, 112]
puts packed.encoding # => ASCII-8BIT

Common Format Directives

Directive Description Size
C / c 8-bit unsigned / signed integer 1 byte
n / v 16-bit unsigned big-endian / little-endian 2 bytes
N / V 32-bit unsigned big-endian / little-endian 4 bytes
q> / q< 64-bit signed big-endian / little-endian 8 bytes
Q> / Q< 64-bit unsigned big-endian / little-endian 8 bytes
e / g Single-precision float (little / big-endian) 4 bytes
E / G Double-precision float (little / big-endian) 8 bytes
H* / h* Hex string (high nibble first / low nibble first) Variable
a* / A* Arbitrary binary string (null-padded) / space-padded string Variable

4. Unpacking Binary Data (String#unpack and unpack1)

Use String#unpack to decode a binary buffer into an array of values, or String#unpack1 to directly retrieve the first element:

# Binary payload (e.g., from network packet or binary header)
payload = [42, 3.14159].pack('NE')

# Unpack both fields
id, ratio = payload.unpack('NE')
puts "ID: #{id}, Ratio: #{ratio.round(5)}"
# => ID: 42, Ratio: 3.14159

# Unpack only the first field directly with unpack1
first_field = payload.unpack1('N')
puts first_field # => 42

5. Binary File and Socket I/O

When reading or writing binary data on disk or over network sockets, ensure binary mode is active to prevent newline conversion (especially on Windows):

# Reading binary files
raw_data = File.binread('image.png')
puts "Read #{raw_data.bytesize} bytes"

# Writing binary files
header = [0x89, 0x50, 0x4E, 0x47].pack('C*') # PNG magic number
File.binwrite('output.bin', header)

# Using standard File.open with 'wb' or 'rb' flags
File.open('data.bin', 'wb') do |file|
  file.binmode # Ensures no CRLF translation
  file.write([1, 2, 3, 4].pack('C*'))
end

6. Streaming Binary Buffers with StringIO

To read or write structured binary streams in-memory using file-like methods:

require 'stringio'

buffer = StringIO.new("".b)
buffer.binmode

# Write binary records
buffer.write([100, 200].pack('nn'))
buffer.write("PAYLOAD".b)

# Seek and read
buffer.rewind
val1, val2 = buffer.read(4).unpack('nn')
body = buffer.read

puts "Val1: #{val1}, Val2: #{val2}, Body: #{body}"
# => Val1: 100, Val2: 200, Body: PAYLOAD

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents