Converting Binary Data to Hex Strings with HexString in Ruby

I’ve been copying a little utility called HexString around for about three years now. It’s a small extension to Ruby’s String class that provides methods String#to_hex_string and String#to_byte_string, which generate new strings by either:

  • transforming all the bytes in a string into space-delimited string containing hexadecimal tuples, for human consumption
  • converting a human-readable string of hexadecimal digits into a string of their corresponding byte values

HexString came into being a few years back when my team was implementing a number of parsers and generators for a proprietary binary file format. In our unit tests, we found it more elegant to express our expectations for certain data segments, and to express binary test inputs, as String literals that could then be automatically converted into their binary equivalent. For test failure messages, we could also convert chunks of binary data back into their hex string equivalent to create succinct, readable test failure messages.

(Usage examples from the file:)

# Load HexString and automatically extend String:
require 'hex_string'

# Convert data to human-readable hex tuples:
>> "hello".to_hex_string
=> "68 65 6c 6c 6f"

# Compact a hex string into its data equivalent:
>> "77 6f 72 6c 64".to_byte_string
=> "world"

# (#to_byte_string is space and case-insensitive:)
>> "776F726C64".to_byte_string
=> "world"

# Peek at the first 4 bytes of an executable on OS X:
=> "ca fe ba be"

In any application where we found ourselves handling binary data, we found HexString to be a pleasant little helper. A quick search of my hard drive just now reveals over a dozen repositories containing some copy hex_string.rb.

Shame on me for not publishing this gem earlier, given how often I went looking for a copy.

Don’t get me wrong: HexString is not a fully-fledged binary formatting toolkit. It doesn’t even format or parse multibyte values like ints and shorts. It’s just… handy. Certainly easier than drumming up memories of cryptic calls to Array#pack and String#unpack and format("%02x").

  • הובלות דירות…

    … הובלות דירות – ראשית, עליכם לוודא כי הצעות מחיר ריאליות ולבחור בחברת ההובלות. הובלה בתנאים הובלות דירות, העברת חפצים יקרי ערך וכל פרט בסיסי אחר כמו הימצאותה של בבניין. באתר no problem הובלות ד… Converting binary data to hex strings with HexString…

  • Comments are closed.