Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java converting int to hex and back again

Tags:

java

string

hex

I have the following code...

int Val=-32768; String Hex=Integer.toHexString(Val); 

This equates to ffff8000

int FirstAttempt=Integer.parseInt(Hex,16); // Error "Invalid Int" int SecondAttempt=Integer.decode("0x"+Hex);  // Error "Invalid Int" 

So, initially, it converts the value -32768 into a hex string ffff8000, but then it can't convert the hex string back into an Integer.

In .Net it works as I'd expect, and returns -32768.

I know that I could write my own little method to convert this myself, but I'm just wondering if I'm missing something, or if this is genuinely a bug?

like image 358
Rich S Avatar asked Aug 17 '12 12:08

Rich S


People also ask

Can java automatically convert int to double?

Since double has longer range than int data type, java automatically converts int value to double when the int value is assigned to double. 1. Java implicit conversion from int to double without typecasting.

What is toHexString?

toHexString() is a built-in function in Java which returns a string representation of the integer argument as an unsigned integer in base 16. The function accepts a single parameter as an argument in Integer data-type.

How do I convert an int to a number in java?

just use constructor of Number class.


2 Answers

int val = -32768; String hex = Integer.toHexString(val);  int parsedResult = (int) Long.parseLong(hex, 16); System.out.println(parsedResult); 

That's how you can do it.

The reason why it doesn't work your way: Integer.parseInt takes a signed int, while toHexString produces an unsigned result. So if you insert something higher than 0x7FFFFFF, an error will be thrown automatically. If you parse it as long instead, it will still be signed. But when you cast it back to int, it will overflow to the correct value.

like image 159
brimborium Avatar answered Oct 21 '22 00:10

brimborium


It overflows, because the number is negative.

Try this and it will work:

int n = (int) Long.parseLong("ffff8000", 16); 
like image 31
roni bar yanai Avatar answered Oct 20 '22 22:10

roni bar yanai