Converting a Decimal to an Arbitrary Base
posted
Tuesday, June 24 at 02:05AM
Leah posted her solution for encoding a decimal number to a "strange base 56 set" to illustrate how Pownce will be providing shortened URLs. As a fun diversion, I wrote my own encoder:
# My Ruby encoder
to_base = Proc.new {|number, table, base| base ||= table.length; number.zero? ? "" : to_base.call(number / base, table, base) + table[number % base].to_s }
# Leah's example data
t = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ".split("")
n = 2477365
puts to_base.call(n, t)
# puts g7YF
Mine is probably both slower and less memory-efficient, but I wanted to do a non-iterative solution.