Java converting int to hex and back again

前端 未结 10 1161
鱼传尺愫
鱼传尺愫 2020-11-28 08:34

I have the following code...

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

This equates to ffff8000

int         


        
10条回答
  •  天涯浪人
    2020-11-28 09:06

    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.

提交回复
热议问题