Java negative int to hex and back fails

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

    This seem to work for me :

    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((int)Long.parseLong(minHex, 16));
    }
    }
    

    The integer is parsed as a "signed long" that handle such big positive number and then the sign is found back by casting it to "int".

提交回复
热议问题