Java negative int to hex and back fails

后端 未结 6 1723
北荒
北荒 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:19

    You need to include a negative sign.

    I don't have access to test this right now but I'd bet if you tried this value instead:

    Integer min = Integer.MIN_VALUE + 1;
    

    It wouldn't bomb, but would give you a positive number (not negative) when you ran ParseInt(min,16).

    A string of bits doesn't really have enough info to determine sign in this context so you need to provide it. (consider the case where you use min = "F". Is that +/-F? If you converted it to bits and saw 1111, and you knew it was a byte, you might conclude that it's negative, but that's a lot of ifs.

提交回复
热议问题