Base64 and hex encoding
suggest changeConverting binary data to safe ASCII representations—such as Base64 and Hexadecimal (Base16)—is essential when embedding binary payloads in JSON, HTTP headers, URLs, or database fields. Ruby provides native standard library modules and core string methods to handle both encodings efficiently.
1. Base64 Encoding (require 'base64')
The standard library module Base64 provides multiple encoding schemes:
require 'base64'
data = "Hello, Ruby Developers!"
Standard vs Strict Base64
Base64.encode64: Adds newline (\n) characters every 60 characters and at the end of the output (MIME RFC 2045 format).Base64.strict_encode64: Produces a single contiguous string without newlines (RFC 4648 format, recommended for APIs, Authorization headers, and JSON).
require 'base64'
# Strict encoding (no newlines)
strict_encoded = Base64.strict_encode64("SecretPayload123")
puts strict_encoded
# => U2VjcmV0UGF5bG9hZDEyMw==
# Decoding strict or standard base64
decoded = Base64.decode64(strict_encoded)
puts decoded
# => SecretPayload123
URL-Safe Base64
Standard Base64 uses + and /, which have special meanings in URLs and file systems. URL-safe Base64 substitutes - and _ and allows stripping = padding:
require 'base64'
raw = "\xFB\xFF\xFE\x00\x01"
# URL-safe encoding (RFC 4648 §5)
url_safe = Base64.urlsafe_encode64(raw)
puts url_safe # Uses '-' and '_' instead of '+' and '/'
# Without '=' padding (common for JWT tokens)
jwt_safe = Base64.urlsafe_encode64(raw, padding: false)
puts jwt_safe
# Decoding URL-safe Base64
original = Base64.urlsafe_decode64(url_safe)
2. Hexadecimal Encoding (Hex / Base16)
Binary to Hex with unpack1('H*')
The most common and performant idiom in Ruby to convert binary bytes to a lowercase hex string uses unpack1('H*'):
binary_data = "Ruby".b
# Encode binary to hex string
hex_str = binary_data.unpack1('H*')
puts hex_str # => 52756279
Hex to Binary with Array#pack('H*')
To convert a hexadecimal string back into raw binary bytes:
hex_str = "52756279"
# Decode hex to binary
raw_bytes = [hex_str].pack('H*')
puts raw_bytes # => "Ruby"
3. Numeric Hex Conversions
For integers and byte values:
# Integer to Hex String
number = 255
puts number.to_s(16) # => "ff"
puts number.to_s(16).upcase # => "FF"
puts sprintf("0x%04X", 255) # => "0x00FF" (zero-padded 4 digits)
# Hex String to Integer
puts "ff".hex # => 255
puts "0xFF".to_i(16) # => 255
4. Cryptographic Hashes in Hex
The built-in digest and openssl libraries produce hexadecimal strings directly:
require 'digest'
require 'base64'
# SHA-256 in Hex format
hash_hex = Digest::SHA256.hexdigest("user-password-or-data")
puts hash_hex
# => 64-character lowercase hex string
# Binary digest converted to Base64
hash_bin = Digest::SHA256.digest("user-password-or-data")
hash_b64 = Base64.strict_encode64(hash_bin)
puts hash_b64
5. Summary Reference Table
| Goal | Method | Output Example |
|---|---|---|
| Single-line Base64 | Base64.strict_encode64(str) |
"SGVsbG8=" |
| URL-safe Base64 | Base64.urlsafe_encode64(str) |
"-_8=" |
| Decode Base64 | Base64.decode64(b64) |
"Hello" |
| Binary to Hex | str.unpack1('H*') |
"48656c6c6f" |
| Hex to Binary | [hex].pack('H*') |
"Hello" |
| Int to Hex | n.to_s(16) |
"ff" |
| Hex to Int | hex.to_i(16) or hex.hex |
255 |