Class: Bagua::Hex

Inherits:
Object
  • Object
show all
Defined in:
lib/bagua/hex.rb

Overview

Provides encoding and decoding functions for hexagrams.

Class Method Summary collapse

Class Method Details

.decode(grams, sequence = :binary) ⇒ Object

Note:

Chomps trailing null characters, as they are the result of zero padding added when the number of bits being encoded in the hexagrams is not an even multiple of 6.

Decodes a string of hexagrams into a UTF-8 string.



14
15
16
# File 'lib/bagua/hex.rb', line 14

def self.decode(grams, sequence = :binary)
  return to_bytes(grams, sequence).pack('C*').chomp("\000").force_encoding('utf-8')
end

.encode(str, sequence = :binary) ⇒ Object

Encodes a string into a string of hexagrams representing the byte values of each character in the string.



6
7
8
# File 'lib/bagua/hex.rb', line 6

def self.encode(str, sequence = :binary)
  return from_bytes(str.unpack('C*'), sequence)
end

.from_bytes(bytes, sequence = :binary) ⇒ Object

Returns the hexagram representation of the input bytes.



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/bagua/hex.rb', line 19

def self.from_bytes(bytes, sequence = :binary)
  sextets = Bagua::bytes_to_ntets(bytes, 6)

  if (sequence == :wen)
    return sextets.map { |sextet| gram(sextet) }.join("")
  elsif (sequence == :binary)
    return sextets.map { |sextet| gram_bin(sextet) }.join("")
  else
    raise "invalid sequence type"
  end
end

.to_bytes(grams, sequence = :binary) ⇒ Object

Returns the byte representation of a string of hexagrams.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/bagua/hex.rb', line 32

def self.to_bytes(grams, sequence = :binary)
  ucodes = grams.unpack('U*')

  sextets = ucodes.map { |ucode| ucode - HEX_BASE }

  if (sequence == :wen)
  elsif (sequence == :binary)
    wen_to_bin = BIN_TO_WEN.invert()
    sextets.map! { |sextet| wen_to_bin[sextet]}
  else
    raise "invalid sequence type"
  end
  
  bytes = Bagua::ntets_to_bytes(sextets, 6)
  return bytes
end