Search code examples
javabinarydecimalnumberformatexception

NumberFormatException while trying to print reverse of 32 bit binary number


I am trying to print reverse of a 32 bit binary number in decimal format: Example:

x = 3, 00000000000000000000000000000011 => 11000000000000000000000000000000

return 3221225472

I am getting a number format exception, can anyone please help me whats wrong in my code? I appreciate your help.

public class ReverseBinary {

    public long reverse(long a) {

        String s1 = String.format("%32s", Long.toBinaryString(a)).replace(' ', '0');
        StringBuilder sb = new StringBuilder(s1);
        String s = sb.reverse().toString();

        long c = Integer.parseInt(s, 2);

        return c;
    }

    public static void main(String args[]) {
        ReverseBinary rb = new ReverseBinary();

        long ans = rb.reverse(3);

        System.out.println(ans);
    }
}

Solution

  • Your variable c might be a long variable, but the value delivered by Integer.parseInt(s,2) is still an integer. This call tries to parse an integer value which causes problems, because the value is obviously out of the integer range.

    Simply replace Integer.parseInt(s,2) by Long.parseLong(s, 2).