Thursday, August 12, 2010

Formatting Hex Strings in Ruby

This method converts a 1 or 2 character string representing a hex number into a 2 character string representing a hex number.

Usage examples:

irb(main):001:0>format("a")
=> "0A"
irb(main):002:0>format("2D")
=> "2D"


Implementation:

def format_hex_string(byte)
    byte.upcase
    byte.to_i(16) >= 16 ? byte : "0" + byte
end

No comments:

Post a Comment