class Bagua::Hex
Provides encoding and decoding functions for hexagrams.
Constants
- BIN_TO_WEN
Binary sequence mapping for hexagram characters. This is needed because the hexagram characters are ordered by King Wen's sequence in Unicode.
- HEX_BASE
Decimal representation of the Unicode code point of the first hexagram character. The code point for any hexagram can by obtained by adding an offset between 0 and 63 to
HEX_BASE
.
Public Class Methods
Decodes a string of hexagrams into a UTF-8 string. @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.
# 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
Encodes a string into a string of hexagrams representing the byte values of each character in the string.
# File lib/bagua/hex.rb, line 6 def self.encode(str, sequence = :binary) return from_bytes(str.unpack('C*'), sequence) end
Returns the hexagram representation of the input bytes.
# 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
Returns the byte representation of a string of hexagrams.
# 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
Private Class Methods
Returns the hexagram in King Wen's sequence that corresponds to the number num. @note If num >= 64, only the lowest six bits are used.
# File lib/bagua/hex.rb, line 128 def self.gram(num) return [HEX_BASE + (num & 63)].pack('U') end
Returns the hexagram in binary sequence that corresponds to the number num. @note If num >= 64, only the lowest six bits are used.
# File lib/bagua/hex.rb, line 135 def self.gram_bin(num) return gram(BIN_TO_WEN[num & 63]) end