Module: Binascii::Hex

Included in:
Binascii
Defined in:
lib/binascii/hex.rb

Constant Summary collapse

A2B_LO =
(('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a)
.each_with_object({}) { |chr, ret| ret[chr.ord] = chr.to_i(16) }
.freeze
A2B_HI =
A2B_LO
.each_with_object({}) { |(ord, idx), ret| ret[ord] = idx << 4 }
.freeze
B2A =
(0...256).each_with_object({}) do |b, ret|
  ret[b] = b.to_s(16).rjust(2, '0')
end.freeze

Instance Method Summary collapse

Instance Method Details

#a2b_hex(data) ⇒ Object Also known as: unhexlify



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/binascii/hex.rb', line 27

def a2b_hex(data)
  String.new('', encoding: 'ASCII-8BIT').tap do |result|
    len = data.bytesize
    pos = 0

    while pos < len
      result << (A2B_HI[data.getbyte(pos)] | A2B_LO[data.getbyte(pos + 1)])
      pos += 2
    end
  end
end

#b2a_hex(data) ⇒ Object Also known as: hexlify



17
18
19
20
21
22
23
# File 'lib/binascii/hex.rb', line 17

def b2a_hex(data)
  String.new('', encoding: 'ASCII-8BIT').tap do |result|
    data.each_byte do |byte|
      result << B2A[byte]
    end
  end
end