Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this hexadecimal value gets different decimal value? [closed]

Tags:

java

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.

like image 654
shimatai Avatar asked Apr 08 '19 21:04

shimatai


1 Answers

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).

like image 175
shimatai Avatar answered Oct 02 '22 11:10

shimatai