javabinaryhexdata-conversionnumber-systems

Inconsistently getting NumberFormatException when trying to convert binary to hex


If use variable bin1 it wont convert, however if i replace the parameter with bin2 it seems to work.

I tried using long instead of int. It's still the same.

public class Test{
    public static void main(String[] args) {
        String bin1 = "11011100000000010001000000000000";
        String bin2 = "01100100001000010001000000000000";

        int dec = Integer.parseInt(bin1, 2);
        String hex = Integer.toString(dec, 16);

        System.out.println(hex);
    }
}

Solution

  • It actually works fine with longs.

    public class Test{
        public static void main(String[] args) {
            String bin1 = "11011100000000010001000000000000";
            String bin2 = "01100100001000010001000000000000";
    
            long dec = Long.parseLong(bin1, 2);
            String hex = Long.toString(dec, 16);
    
            System.out.println(hex);
        }
    }
    

    Result:

    dc011000
    

    Your number is simply too big for an int.