Convert a Long to base 36 in scala

AKnox picture AKnox · Feb 19, 2013 · Viewed 11.7k times · Source

How can I convert a Long to base36 ? Along with your answer can explain how you came to the answer?

I've checked the scaladocs for Long for converting to a different base, and on converting a Long to a BigInt. I saw that BigInt does have toString( base ) so a solution could involve changing the type, but I couldn't figure out how.

Note: I'm new to scala / java / type-safe languages so I could be overlooking something trivial.

Answer

charo picture charo · Mar 24, 2013

Staying within Scala language, converting Long to a BigInt turns out to be simple:

var myLong : Long = Long.MaxValue
var myBigInt : BigInt = myLong
myBigInt.toString(36)

output being:

myLong: Long = 9223372036854775807
myBigInt: scala.math.BigInt = 9223372036854775807
res199: String = 1y2p0ij32e8e7

They way I came to topic was as a Java developer and Scala beginner (reading chapter 1 of "Scala for the Impatient.pdf"). The answers above worked but seemed strange. Having to jump into Java land for such a basic conversion seemed less correct somehow, especially when BigInt had all the stuff. After reviewing scaladoc and the answers above, a few fails followed.

My biggest fail was using toInt() which truncates myLong horridly. About to give up, the final attempt seemed so simple and intuitive that I almost didn't try it: myBigInt = myLong. Perhaps one day Long will be richer and understand toBigInt... this was my first fail in the journey.