2

I've got a signed int_32 value (FFFFFFFC) what's representing -4

If I try to convert it by ...

long x = Long.parseLong("FFFFFFFC", 32);
System.out.println("X: " + x);

... I'll get "X: 532021755372" instead of -4. How could I convert it as a signed value?

craCH
  • 103
  • 9
  • This is not a duplicate of "how to parse hex in Java". OP made several mistakes in his code that need to be fixed. Also, the solution is going to be different than any solution discussed in the previously mentioned duplicate. – Sergey Kalinichenko Jul 21 '15 at 13:20

3 Answers3

6

You get an incorrect result because 32 represents the numeric base, not the number of bits in the result. You are parsing the string as a base-32 number (i.e. a number in a numbering system that uses digits 0..9 and letters A..V, not 0..9 and A..F.

To parse the number correctly, use Long.parseLong("FFFFFFFC", 16);, and cast the result to int, which is a 32-bit number:

int x = (int)Long.parseLong("FFFFFFFC", 16);
System.out.println("X: " + x); // Prints X: -4

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

if FFFFFFFC represents -4 it is int, not long, parse it like this

int x = Integer.parseUnsignedInt("FFFFFFFC", 16);

and you will get -4

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

Try this

int x= new BigInteger("FFFFFFFC", 16).intValue();
System.out.println("X: " + x);