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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With