Skip to content

Instantly share code, notes, and snippets.

@benders
Created May 13, 2009 18:19
Show Gist options
  • Save benders/111182 to your computer and use it in GitHub Desktop.
Save benders/111182 to your computer and use it in GitHub Desktop.
Example methods for converting Integers to and from bases over 36
#!/usr/bin/env ruby -wKU
B64_ALPHABET = ('0'..'9').to_a + ('a'..'z').to_a + ('A'..'Z').to_a + ['+', '/']
class Integer
def to_s64( base = 64 )
input = self
out = ""
while input > 0
digit = input % base
out = B64_ALPHABET[digit] + out
input = (input - digit) / base
end
out
end
end
class String
def to_i64( base = 64 )
result = 0
self.each_byte do |char|
value = B64_ALPHABET.index(char.chr)
if value.nil? or value >= base then
return result
end
result *= base
result += value
end
return result
end
end
if $0 == __FILE__
p = [2, 5, 13, 64, 128, 255]
p.each do |x|
s = x.to_s64(52)
i = s.to_i64(52)
puts "#{x} == #{s} == #{i}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment