I want to dynamically set an integer variable using a hexadecimal value, but when I use Integer.parse(hexValue, 16)
it gets a different value from setting as int a = 0x04A7D488
For example:
int a = 0x04A7D3B8;
System.out.println("a = " + a); // prints 78107576
int b = Integer.parseInt("04A7D3B8", 16);
System.out.println("b = " + b); // prints 78107784
Why do I get different values? How can I dynamically set variable a
with value 0x04A7D3B8
?
Note: I've discovered that this error is only happening with Java SDK 1.8.0_171.
Solution
I was trying to convert a negative integer value using Long.parseLong
or Integer.parseInt
, but the correct solution is using Integer.parseUnsignedInt("FD8914EC");
In my tests, the value FD8914EC
was converting to -41347860
(declaring as long a = 0xFD8914EC
) or 4253619436
(declaring as long b = Long.parseLong("FD8914EC", 16);
), but you have always to use Integer.parseUnsignedInt
(the result will be negative if the hexadecimal value starts with F
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With