Java converting int to hex and back again

前端 未结 10 1115
鱼传尺愫
鱼传尺愫 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:04

    It's worth mentioning that Java 8 has the methods Integer.parseUnsignedInt and Long.parseUnsignedLong that does what you wanted, specifically:

    Integer.parseUnsignedInt("ffff8000",16) == -32768

    The name is a bit confusing, as it parses a signed integer from a hex string, but it does the work.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 09:08

    As Integer.toHexString(byte/integer) is not working when you are trying to convert signed bytes like UTF-16 decoded characters you have to use:

    Integer.toString(byte/integer, 16);
    

    or

    String.format("%02X", byte/integer);
    

    reverse you can use

    Integer.parseInt(hexString, 16);
    
    0 讨论(0)
  • 2020-11-28 09:08

    Below code would work:

    int a=-32768;
    String a1=Integer.toHexString(a);
    int parsedResult=(int)Long.parseLong(a1,16);
    System.out.println("Parsed Value is " +parsedResult);
    
    0 讨论(0)
提交回复
热议问题