Skip to content

Instantly share code, notes, and snippets.

@lian
Created November 6, 2013 22:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lian/7345750 to your computer and use it in GitHub Desktop.
Save lian/7345750 to your computer and use it in GitHub Desktop.
base32.rb
module Base32
TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".downcase
class Chunk < Struct.new(:bytes)
def decode
b = bytes.take_while{|c| c != 61 } # strip padding
n = (b.length * 5.0 / 8.0).floor
p = b.length < 8 ? 5 - (n * 8) % 5 : 0
c = b.inject(0){|m,o| (m << 5) + TABLE.index(o.chr) } >> p
(0...n).to_a.reverse.map{|i| ((c >> i * 8) & 0xff).chr }
end
def encode
n = (bytes.length * 8.0 / 5.0).ceil
p = n < 8 ? 5 - (bytes.length * 8) % 5 : 0
c = bytes.inject(0){|m,o| (m << 8) + o } << p
[(0...n).to_a.reverse.map{|i| TABLE[(c >> i * 5) & 0x1f].chr }, ("=" * (8-n))]
end
end
def self.chunks(str, size);
str.bytes.each_slice(size).map{|i| Chunk.new(i) }
end
def self.encode(str); chunks(str, 5).map(&:encode).flatten.join; end
def self.decode(str); chunks(str, 8).map(&:decode).flatten.join; end
end
p Base32.encode( Base32.decode("rc3no6ludp4ozphw") ) == "rc3no6ludp4ozphw"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment