Hex String to Int,Short and Long in Scala

7zark7 answer is correct, but I want to make some additions. Implicit from String to Int can be dangerous. Instead you can use implicit conversion to wrapper and call parsing explicitly:

class HexString(val s: String) {
    def hex = Integer.parseInt(s, 16)
}
implicit def str2hex(str: String): HexString = new HexString(str)

val num: Int = "CAFE".hex

What about a one-liner?

def hexToInt(s: String): Int = {
    s.toList.map("0123456789abcdef".indexOf(_)).reduceLeft(_ * 16 + _)
}

scala> hexToInt("cafe")
res0: Int = 51966

And to answer your second item:

Is there something like "A".toInt(base)?

Yes, still as a one-liner:

def baseToInt(s: String, base: String): Int = {
    s.toList.map(base.indexOf(_)).reduceLeft(_ * base.length + _)
}

scala> baseToInt("1100", "01")
res1: Int = 12

You can use the Java libs:

val number = Integer.parseInt("FFFF", 16)
> number: Int = 65535

Or if you are feeling sparky :-):

implicit def hex2int (hex: String): Int = Integer.parseInt(hex, 16)

val number: Int = "CAFE" // <- behold the magic
number: Int = 51966

Also, if you aren't specifically trying to parse a String parameter into hex, note that Scala directly supports hexadecimal Integer literals. In this case:

val x = 0xCAFE
> x: Int = 51966

Isn't Scala wonderful? :-)

Tags:

Scala