Module: Kernel
- Defined in:
- lib/hexutils.rb
Instance Method Summary collapse
- #decode_hex(hex) ⇒ Object (also: #hex)
-
#encode_hex(bin) ⇒ Object
bin_to_hex.
Instance Method Details
#decode_hex(hex) ⇒ Object Also known as: hex
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/hexutils.rb', line 71 def decode_hex( hex ) ## use ArgumentError or TypeError - why? why not? raise TypeError, "Value must be a string" unless hex.is_a?( String ) ## note: for now allow whitespaces - get auto-removed - why? why not? hex = hex.gsub( /[ \t\r\n]/, '' ) if hex.empty? ## special case - empty string ''.b else raise TypeError, 'Non-hexadecimal char found' unless hex =~ /\A(0[xX])?[0-9a-fA-F]+\z/ ## allow optional starting 0x - why? why not? hex = hex[2..-1] if ['0x', '0X'].include?( hex[0,2] ) hex = '0'+hex if hex.size.odd? [hex].pack('H*') end end |
#encode_hex(bin) ⇒ Object
bin_to_hex
63 64 65 66 67 68 |
# File 'lib/hexutils.rb', line 63 def encode_hex( bin ) ## bin_to_hex ## use ArgumentError or TypeError - why? why not? raise TypeError, "Value must be a string" unless bin.is_a?( String ) ## note: always return a hex string with default encoding e.g. utf-8 - why? why not? bin.hex end |