Created
May 13, 2009 18:19
-
-
Save benders/111182 to your computer and use it in GitHub Desktop.
Example methods for converting Integers to and from bases over 36
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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