Java negative int to hex and back fails

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

    According the the documentation, toHexString returns "a string representation of the integer argument as an unsigned integer in base 16. "

    So the correct reverse operation is probably Integer.parseUnsignedInt that was introduced as part of Java 8:

    public class Main3 {
        public static void main(String[] args) {
            Integer min = Integer.MIN_VALUE;
            String minHex = Integer.toHexString(Integer.MIN_VALUE);
    
            System.out.println(min + " " + minHex);
            System.out.println(Integer.parseUnsignedInt(minHex, 16));
        }
    

提交回复
热议问题