Home > Blockchain >  convert string to hex throws java.lang.NumberFormatException
convert string to hex throws java.lang.NumberFormatException

Time:04-24

I have a color like #FFFFFF and i want to convert it to 0xFFFFFF

here is my code that converts it:

val hexColor = "0x${picture.color.drop(1)}".toInt()

when I run the project I get this error:

Exception in thread "main" java.lang.NumberFormatException: For input string: 
"0xFFFFFF"

any idea why I get this error?

CodePudding user response:

If you want to just convert FFFFFF to 0xFFFFFF, then there is no need for .toInt() and the rest your code should work just fine.

If you want to convert the value of the color from hex to decimal, then you can use .toInt(16) function without the radix (0x) at the beginning, like this:

val color = picture.color.drop(1).toInt(16)

Or using Integer.decode(), like this:

val color = Integer.decode("0x${picture.color.drop(1)}")

CodePudding user response:

In the expression "0x${picture.color.drop(1)}".toInt() the 0x is being added to the string and then being converted to an Int. 0x has no meaning to an Int. So convert it to an Int first:

"0x${picture.color.drop(1).toInt()}"
// #FFFFFF --> 0x16777215 (wrong)

Of course, putting 0x before decimal digits changes its meaning/value. So convert just the Int number to hex:

"0x${picture.color.drop(1).toInt(16).toString(16)}"
// #FFFFFF --> 0xffffff  (lowercase because that's how it's represented)

But it's a hex string. And what you had before was already a hex string, with an extra # before it. So just drop that and add the 0x:

"0x${picture.color.drop(1)}"
// #FFFFFF --> 0xFFFFFF

If you want to store the colour as int and print it in hex, then combine part 1 and 2:

val actualColourValue = picture.color.drop(1).toInt(16)
println(actualColourValue)  // 16777215
println("0x${actualColourValue.toString(16)}")  // 0xffffff

CodePudding user response:

In order to convert a hexadecimal String to a base10-number and back, pass the base as an argument to the toInt()-method: Use toInt(16) for Hex numbers.

  • Related