Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an integer from base 36 to base 10?

Tags:

ruby

I'd like to encode an integer as base 36, and then decode it to base 10. The encoding step is easy:

12345.to_s(36)
=> "9ix"

Now I'd like to decode that back into a base 10 integer. But this doesn't work:

"9ix".to_i(10)
=> 9

So how do I write

def base36to10(36)
  # ?
end

so that

r = rand(100000)
base36to10(r.to_s(36)) == r

?

like image 315
Mori Avatar asked Nov 14 '13 03:11

Mori


1 Answers

You're not converting from base 10, you're converting from base 36, e.g., in Ruby console or irb:

> "9ix".to_i(36)
#=> 12345

Paraphrased from the docs:

Returns result of interpreting str as integer base base (between 2 and 36).

That said, isn't converting numbers between bases trivial? Iterate over the chars, multiply, add.

like image 50
Dave Newton Avatar answered Sep 24 '22 23:09

Dave Newton