Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex String to Int,Short and Long in Scala

Tags:

scala

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)?

like image 829
rsan Avatar asked May 26 '12 05:05

rsan


People also ask

How can I convert a hex string to an integer value?

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.

How do I convert a string to an int in Scala?

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?

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.


2 Answers

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? :-)

like image 100
7zark7 Avatar answered Oct 02 '22 13:10

7zark7


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 
like image 20
Sergey Passichenko Avatar answered Oct 02 '22 13:10

Sergey Passichenko