Why can I parse an 8 digit hex to a Long and convert it to an Integer, but not parse it as an Integer directly?
I am trying to use ColorDrawable(int color)
. This class has a constructor int
. You can usually do something like this:
ColorDrawable(0xFF8E8F8A)
But since I am getting my color as String (6 hex digits, no alpha) I have to do this:
Long color = Long.parseLong("FF"+hexColorString, 16); // hexColorString like "8E8F8A"
ColorDrawable drawable = new ColorDrawable(color.intValue());
Why Integer.parseInt("FF"+hexColorString, 16)
doesn't it return me a negative (effectively unsigned) int instead of throwing it NumberFormatException
?
EDIT: A shorter version of my question:
Why Long.parseLong("FF"+hexColorString, 16).intValue()
and Integer.parseInt("FF"+hexColorString, 16)
do not return the same value? The former works, but the latter gives me an exception.
EDIT: I was not getting the correct color anyway, so I moved on to the next method:
ColorDrawable drawable = new ColorDrawable(Color.parseColor("#FF"+hexColorString));
The value 0xFF8E8F8A
is > Integer.MAX_VALUE
.
Since no overflow or underflow throws Exception
over the design, it will instead interpret your value as Integer.MIN_VALUE
because it Integer.MAX_VALUE + 1
goes into Integer.MIN_VALUE
.
So, it Long.intValue
will convert the value to int
, which, given the value Integer.MAX_VALUE + x
, where x > 0
, will shift from Integer.MIN_VALUE
, i.e. Integer.MIN_VALUE + x
...
However, from the Integer
javadoc:
An exception of type NumberFormatException is thrown if any of the following situations occur:
The first argument is null or a zero-length string. [...] the value represented by the string is not an int.
The value is 0xFF8E8F8A
not type-specific int
, therefore NumberFormatException
.
As a side note, I'm pretty sure the constructor ColorDrawable
accepts int
because instead of numerically representing your color it accepts an ID, but to be honest, the documentation is not entirely clear for this.
See the R.color
documentation here .
Final note - credit goes to the OP on this one.
You can use new ColorDrawable(Color.parseColor(yourHexString))
for a more convenient approach.
Because it 0xFF8E8F8A
is outside the integer range. That is, 0xFF8E8F8A
== 4287532938
, and it is greater than Integer.MAX_VALUE
.
The assumption that 0xFF8E8F8A
equals -7434358
(the value you get when parsing through Long) is wrong, since you can parse negative hex values:
Integer.parseInt("-717076", 16);
So -0x717076
is equal -7434358
and the unsigned representation is 0xFF8E8F8A
.