Module: BytesHelper

Included in:
Bytes
Defined in:
lib/bytes.rb

Constant Summary collapse

HEX_RE =

more helpers check if it is a hex (string)

- allow optiona 0x or 0X  and allow abcdef and ABCDEF
/\A(?:0x)?[0-9a-f]*\z/i

Instance Method Summary collapse

Instance Method Details

#bin_to_hex(bin) ⇒ Object Also known as: btoh



27
28
29
30
31
32
33
34
35
# File 'lib/bytes.rb', line 27

def bin_to_hex( bin )
  # note: unpack returns string with <Encoding:US-ASCII>
  # convert to default encoding
  ##  todo/fix: do NOT hardcode UTF-8 - use default encoding - why? why not?
  hex = bin.unpack('H*').first
  ## note: hexdigits/chars (0-9a-f) should be safe, that is, always ASCII-7BIT/UTF_8 with needing to change any char codes
  hex.encode!( Encoding::UTF_8 )
  hex
end

#hex_to_bin(hex) ⇒ Object Also known as: htob

Raises:

  • (TypeError)


11
12
13
14
15
16
17
18
19
20
21
# File 'lib/bytes.rb', line 11

def hex_to_bin( hex )
  ## todo/fix:  do an argument regex hex check!!!!
  raise TypeError, "BytesHelper.hex_to_bin - non-hexadecimal digit found in >#{hex}<" unless is_hex?( hex )

  ## note: assume pack always returns string with BINARY/ASCII-8BIT encoding!!!
  if ['0x', '0X'].include?( hex[0,2] )   ## cut-of leading 0x or 0X if present
    [hex[2..-1]].pack('H*')
  else
    [hex].pack('H*')
  end
end

#is_hex?(str) ⇒ Boolean

Returns:

  • (Boolean)


46
# File 'lib/bytes.rb', line 46

def is_hex?( str )  !HEX_RE.match( str ).nil?; end