Search code examples
javascalanumber-formattingnumberformatexception

java.lang.Integer.parseInt fails with hex strings hat use the highest bit


I was surprised that the following forward backward conversion from 32-bit ints to hex strings fails:

Integer.parseInt(-2028332484.toHexString, 16)

Gives:

java.lang.NumberFormatException: For input string: "871a1a3c"

Obviously a workaround is

java.lang.Long.parseLong(-2028332484.toHexString, 16).toInt

But I wonder if there is not a better (and possibly more Scala'ish) solution?


Solution

  • It's been answered for Java already here.

    Unfortunately there is no additional treatment for that transformation in scala AFAIK.

    Scala defines in RichInt:

    def toHexString: String = java.lang.Integer.toHexString(self)
    

    and in StringLike:

    def toInt: Int         = java.lang.Integer.parseInt(toString)
    

    apart from import java.lang.{Long => JLong} and using JLong I don't know a more scala-ish solution than yours.