Can somebody please explain why the second and the third of the following statements fail?
Integer myColor = 0xff80CBC4 //works
Integer.parseInt("0xff80CBC4".substring(2), 16) //does not work
Integer.decode("0xff80CBC4") //does not work
When run, the following exception is thrown:
java.lang.NumberFormatException: Invalid int: "ff80CBC4"
If you use 00
instead of ff
at the start of ff80CBC4
, it works. Why does it fail with ff
?
Please note that there is no such thing as "it does not work". Exceptions are issued. Mention them.
Integer.parseInt()
and Integer.decode()
fail because the literal 0xff80CBC4 that you are trying to parse is too large for a signed integer to represent it. (Read-up on two's complement notation to find out why.)
The truth is that it could have been interpreted as a negative integer, but these functions do not know that, so they try to parse it as a positive integer.
Try this:
String s = "0xff80CBC4";
int a = Integer.parseInt( s.substring( 2, 4 ), 16 );
int r = Integer.parseInt( s.substring( 4, 6 ), 16 );
int g = Integer.parseInt( s.substring( 6, 8 ), 16 );
int b = Integer.parseInt( s.substring( 8, 10 ), 16 );
int argb = a << 24 | r << 16 | g << 8 | b;
System.out.printf( "%2x %2x %2x %2x %8x\n", a, r, g, b, argb );
It prints:
ff 80 cb c4 ff80cbc4