Class: Base32::Crockford
- Inherits:
-
Object
- Object
- Base32::Crockford
- Defined in:
- lib/base32/crockford.rb
Constant Summary collapse
- ENCODE =
"0123456789ABCDEFGHJKMNPQRSTVWXYZ"
- DECODE =
{ '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'J' => 18, 'K' => 19, 'M' => 20, 'N' => 21, 'P' => 22, 'Q' => 23, 'R' => 24, 'S' => 25, 'T' => 26, 'V' => 27, 'W' => 28, 'X' => 29, 'Y' => 30, 'Z' => 31, }
Class Method Summary collapse
Class Method Details
.decode(v, to = :binary_string) ⇒ Object
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/base32/crockford.rb', line 89 def self.decode v, to = :binary_string normalized = v.upcase.tr("OILU", "011").tr("-", "").reverse n = 0 bits = 0 res = "" res.force_encoding("binary") if res.respond_to?(:force_encoding) normalized.each_byte do |b| n += (DECODE[ b.chr ] << bits) bits += 5 while bits >= 8 do res << (n & 255).chr n >>= 8 bits -= 8 end end res << n if n != 0 res << 0 if res.empty? res = res.reverse case to when :integer v = 0 res.each_byte do |byte| v <<= 8 v |= byte end v else res end end |
.encode(v) ⇒ Object
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/base32/crockford.rb', line 59 def self.encode v if v.respond_to?(:integer?) && v.integer? normalized = NormalizedInteger.new(v) else normalized = v.reverse end n = 0 bits = 0 res = "" normalized.each_byte do |b| n += b << bits bits += 8 while bits >= 5 do res << ENCODE[ n & 31 ] n >>= 5 bits -= 5 end end res << ENCODE[ n & 31 ] if n != 0 res << 0 if res.empty? res.reverse end |
.hypenate(v) ⇒ Object
85 86 87 |
# File 'lib/base32/crockford.rb', line 85 def self.hypenate v v.reverse.gsub(/(\w\w\w\w\w)/, "\\1-").gsub(/-$/, "").downcase.reverse end |