简体   繁体   中英

Number Format Exception when parse a binary String to an integer

    public static void main(String[] args) {
        int val1 = 700173;
        int val2 = 700173;
        int val3 = 700173;
        int val4 = 700173;
        
        String string1 = Integer.toBinaryString(val1);
        String string2 = Integer.toBinaryString(val2);
        String string3 = Integer.toBinaryString(val3);
        String string4 = Integer.toBinaryString(val4);
        
        String binaryString = string1 + string2 + string3 + string4;
        
        System.out.println(binaryString);
        
        System.out.println(Integer.parseInt(binaryString, 2));
        
    }

So I have this block of code where I am taking 4 integers, converting them to binary strings, concatenating them and then reconverting to an Integer.

So I can use Integer.parseInt to convert each string manually. But after concatenating I get a number format exception cause by the last print statement.

I am try to convert this binary string to an integer.

10101010111100001101101010101111000011011010101011110000110110101010111100001101

I think it might be something to do with the length.

Any help would be great to see what i'm missing.

Thank you-

An int can only have 32-bits. That is 81 bits. You could use a BigInteger . Like,

BigInteger bi = new BigInteger("101010101111000011011010101" //
        + "011110000110110101010111" //
        + "10000110110101010111100001101", 2);
System.out.println(bi);

or in your code

System.out.println(new BigInteger(binaryString, 2));

Outputs

807245278494179007835917

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM