Class: Base32::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/base32-alphabets/base.rb

Direct Known Subclasses

Crockford, Kai

Class Method Summary collapse

Class Method Details

.build_binary(alphabet) ⇒ Object

(private) helpers



57
58
59
60
61
62
63
# File 'lib/base32-alphabets/base.rb', line 57

def self.build_binary( alphabet )
  alphabet.each_with_index.reduce({}) do |h, (char,index)|
    # puts "#{char} => #{index} #{'%05b' % index}"
    h[char] = '%05b' % index
    h
  end
end

.decode(str, klass:) ⇒ Object

Converts a base32 string to a base10 integer.



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/base32-alphabets/base.rb', line 27

def self.decode( str, klass: )
  ## note: allow spaces or dashes (-); remove them all first
  str = str.tr( ' -', '' )

  num = 0
  str.reverse.each_char.with_index do |char,index|
    code = klass::NUMBER[char]
    raise ArgumentError, "Value passed not a valid base32 string - >#{char}< not found in alphabet"  if code.nil?
    num += code * (BASE**(index))
  end
  num
end

.encode(num, klass:) ⇒ Object

Converts a base10 integer to a base32 string.



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/base32-alphabets/base.rb', line 11

def self.encode( num, klass: )
  buf = String.new
  while num >= BASE
    ## puts "num=#{num}"
    mod = num % BASE
    ## puts "  mod=#{mod} == #{klass::ALPHABET[mod]}"
    buf = klass::ALPHABET[mod] + buf
    ## puts "buf=#{buf}"
    num = (num - mod)/BASE
  end
  klass::ALPHABET[num] + buf
end

.fmt(str) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/base32-alphabets/base.rb', line 43

def self.fmt( str )
  ## note: allow spaces or dashes (-); remove them all first
  str = str.tr( ' -', '' )

  ## format in groups of four (4) separated by space
  ##  e.g.  ccac7787fa7fafaa16467755f9ee444467667366cccceede
  ##     :  ccac 7787 fa7f afaa 1646 7755 f9ee 4444 6766 7366 cccc eede
  str.reverse.gsub( /(.{4})/, '\1 ').reverse.strip
end