Skip to content

Instantly share code, notes, and snippets.

@manveru
Created February 2, 2009 10:59
Show Gist options
  • Save manveru/56877 to your computer and use it in GitHub Desktop.
Save manveru/56877 to your computer and use it in GitHub Desktop.
module Base62
CHARS = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
MOD = CHARS.size # 62
module_function
def encode_packed(string)
encode(string.unpack('H*').at(0).to_i(16))
end
def encode(fixnum)
out = []
while fixnum > 0
fixnum, r = fixnum.divmod(MOD)
out.unshift CHARS[r]
end
out.join
end
def decode_packed(string)
[decode(string).to_s(16)].pack('H*')
end
def decode(string)
out = 0
string.scan(/./mn){|c| out = out * MOD + CHARS.index(c) }
out
end
end
eval(DATA.read) if __FILE__ == $0
__END__
require 'bacon'
Bacon.summary_on_exit
describe Base62 do
should 'encode' do
Base62.encode(999).should == 'qh'
end
should 'decode' do
Base62.decode('qh').should == 999
end
should 'encode_packed' do
Base62.encode_packed('Hello, World! - snake_case').
should == "ntNEbEbmiA66ycSlgi04nDKpZl1YZM1N7sf"
end
should 'decode_packed' do
Base62.decode_packed("ntNEbEbmiA66ycSlgi04nDKpZl1YZM1N7sf").
should == 'Hello, World! - snake_case'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment