Skip to content

Instantly share code, notes, and snippets.

@umutakturk
Created April 7, 2013 23:26
Show Gist options
  • Save umutakturk/5333063 to your computer and use it in GitHub Desktop.
Save umutakturk/5333063 to your computer and use it in GitHub Desktop.
Based on work done by Tantek Çelik: http://ttk.me/w/NewBase60 | http://ttk.me/w/NewBase64
class BaseConvert
CHARS = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ_abcdefghijkmnopqrstuvwxyz" # !-+*$
BASE = CHARS.length
def self.num_to_str(num = nil)
str = ""
return 0 if num.nil? || num.zero?
while num > 0 do
mod = num % BASE
str = CHARS[mod, 1] + str
num = (num - mod) / BASE
end
str
end
def self.str_to_num(string)
num = 0
string.each_byte do |char|
case char
when 33, 73, 108 then char = 1 # typo capital I, lowercase l, ! to 1
when 36 then char = 63 # dollar sign
when 42 then char = 62 # asterisk
when 44 then char = 61 # plus
when 45 then char = 60 # dash
when 48..57 then char -= 48
when 65..72 then char -= 55
when 74..78 then char -= 56
when 79 then char = 0 # error correct typo capital O to 0
when 80..90 then char -= 57
when 95 then char = 34 # underscore
when 97..107 then char -= 62
when 109..122 then char -= 63
else char = 0 # treat all other noise as 0
end
num = BASE * num + char
end
num
end
class << self
alias_method :encode, :num_to_str
alias_method :decode, :str_to_num
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment