why Java throws a NumberFormatException

前端 未结 3 875
灰色年华
灰色年华 2021-01-15 10:46

I got an exception while parsing a string to byte

String Str =\"9B7D2C34A366BF890C730641E6CECF6F\";

String [] st=Str.split(\"(?<=\\\\G.{2})\");

byte[]by         


        
3条回答
  •  悲哀的现实
    2021-01-15 11:10

    Java is very picky on signedness, it will not accept values to overflow. Thus, if you parse a Byte and it is larger than 127 (for example, 130 dec or 83 hex) you will get a NumberFormatException. Same happens if you parse an 8 digit hex number as an Integer (or a 16 digit hex number as a Long) and it starts with 8-F. Such values will not be interpreted as negative (two's complement) but as illegal.

    If you think that this is anal retentive, I totally agree. But that's Java style.

    To parse hex values as two's complement numbers either use a large enough integer type (for example, if you are parsing a Byte use Integer instead and type cast it to a byte later) or -- if you need to parse a Long, split the number in half it is 16 digits, then combine. Here's an example:

    public static long longFromHex(String s) throws IllegalArgumentException {
        if (s.length() == 16)
            return (Long.parseLong(s.substring(0,8),16)<<32)|(Long.parseLong(s.substring(8,16),16)&0xffffffffL);
        return Long.parseLong(s, 16);
    }
    

    Or, to read a Byte, just use Integer instead:

    public static byte byteFromHex(String s) throws IllegalArgumentException {
        int i = Integer.parseInt(s, 16);
        if (i < 0 || i > 255) throw new IllegalArgumentException("input string "+s+" does not fit into a Byte");
        return (byte)i;
    }
    

提交回复
热议问题