Module: Baseh::BaseN
- Defined in:
- lib/baseh/basen.rb
Overview
Fixed-length base-N encoding, spec section 5. Most significant digit first.
Class Method Summary collapse
- .alphabet_index(alphabet) ⇒ Object
-
.decode_base_n(text, alphabet, index = nil) ⇒ Object
Spec 5.2.
-
.encode_base_n(value, alphabet, length) ⇒ Object
Spec 5.1.
Class Method Details
.alphabet_index(alphabet) ⇒ Object
39 40 41 |
# File 'lib/baseh/basen.rb', line 39 def alphabet_index(alphabet) alphabet.each_char.each_with_index.to_h end |
.decode_base_n(text, alphabet, index = nil) ⇒ Object
Spec 5.2. Raises INVALID_CHARACTER for symbols outside the alphabet.
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/baseh/basen.rb', line 22 def decode_base_n(text, alphabet, index = nil) index ||= alphabet_index(alphabet) base = alphabet.length value = 0 text.each_char do |ch| digit = index[ch] if digit.nil? raise BasehError.new( "INVALID_CHARACTER", "Symbol #{ch.inspect} is not in the alphabet" ) end value = value * base + digit end value end |
.encode_base_n(value, alphabet, length) ⇒ Object
Spec 5.1. All arithmetic stays in Integer (arbitrary precision).
9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/baseh/basen.rb', line 9 def encode_base_n(value, alphabet, length) base = alphabet.length out = Array.new(length) v = value (length - 1).downto(0) do |pos| digit = v % base out[pos] = alphabet[digit] v /= base end out.join end |