Just can't find a way to transform an Hex String to a number (Int, Long, Short) in Scala.
Is there something like "A".toInt(base)
?
To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.
A string can be converted to integer in Scala using the toInt method. This will return the integer conversion of the string. If the string does not contain an integer it will throw an exception with will be NumberFormatException. So, the statement: val i = "Hello".
Does atoi work on hex? atoi(s[,base]) converts a string into an integer. The default is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10.
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? :-)
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
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