Java negative int to hex and back fails

后端 未结 6 1741
北荒
北荒 2020-12-06 06:54
public class Main3 {
    public static void main(String[] args) {
        Integer min = Integer.MIN_VALUE;
        String minHex = Integer.toHexString(Integer.MIN_VA         


        
6条回答
  •  醉酒成梦
    2020-12-06 07:43

    This is something that's always annoyed me. If you initialize an int with a hex literal, you can use the full range of positive values up to 0xFFFFFF; anything larger than 0x7FFFFF will really be a negative value. This is very handy for bit masking and other operations where you only care about the locations of the bits, not their meanings.

    But if you use Integer.parseInt() to convert a string to an integer, anything larger than "0x7FFFFFFF" is treated as an error. There's probably a good reason why they did it that way, but it's still frustrating.

    The simplest workaround is to use Long.parseLong() instead, then cast the result to int.

    int n = (int)Long.parseLong(s, 16);
    

    Of course, you should only do that if you're sure the number is going to be in the range Integer.MIN_VALUE..Integer.MAX_VALUE.

提交回复
热议问题