Search code examples
javabinaryparseint

Converting binary to decimal and flipping 0 and 1 JAVA


    public static int reverseIntBitwise(int value) {
    String res = String.format("%32s", 
    Integer.toBinaryString(value)).replace(' ', '0');

    char[] charArray = res.toCharArray();
    for(int i=0; i<charArray.length; i++){
        if(charArray[i] == '0'){
            charArray[i]='1';
        }else if(charArray[i]=='1'){
            charArray[i]='0';
        }
    }
    String res2 = new String(charArray);
    return Integer.parseInt(res2, 2);
}

So res = 00000000000000000000000000101110 And res2 = 11111111111111111111111111010001

but when I try to convert it back to int this is displayed in the console:

Exception in thread "main" java.lang.NumberFormatException: For input string: "11111111111111111111111111010001"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at com.company.Main.reverseIntBitwise(Main.java:169)
    at com.company.Main.main(Main.java:150)

Can anyone help with resolving this? Thanks


Solution

  • You are getting NumberFormatException because the resultant number 4294967249 is outside of range of Integer (i.e. more than Integer.MAX_VALUE). You can try BigInteger instead, e.g.:

    String res2 = "11111111111111111111111111010001";
    System.out.println(new BigInteger(res2, 2));