简体   繁体   中英

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);
    }
}

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) .

它应该是

long c= Long.parseLong(s,2);

Just in case you want the signed integer that corresponds to the reversed bit pattern: there is a method to just do that.

public class Test
{
    public static void main (String[] args)
    {
        // 000...001 -> 100...000, interpret as two's complement 32bit int
        int reversed = Integer.reverse(0b0_00000000_00000000_00000000_00000001);
        System.out.println(reversed == Integer.MIN_VALUE); // -> true
    }
}

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