简体   繁体   中英

Java converting negative binary back to integer

I'm trying to convert an base 10 number to a base 2 and back to base 10. It works only for positive argument_decimal

argument_binary = Integer.toBinaryString(argument_decimal);
back_converted_argument_decimal = Integer.valueOf(argument_binary, 2);

For argument_decimal beeing negative, I get "java.lang.NumberFormatException: For input string: "11111111111111111111111111111111""

EDIT: here is what I do:

latitude_binary = Integer.toBinaryString((int)(latitude_decimal * 1000000));   
back_converted_latitude_decimal =  Long.parseLong(latitude_binary, 2) / 1000000.0;

which gives me bad results like -1.1 being forth and back converted to 4293.867296

Try to go via a long:

String binary = Integer.toBinaryString(-1);
long l = Long.parseLong(binary, 2);
int i = (int) l;

Tested, and working.

Why this works is because -1 is represented as a sequence of 32 bits 1 in system memory. When using the toBinaryString method, it creates a string using that exact representation. But, 32 bits of one is in fact equal to 2^32 - 1. That is too large for an int (4 bytes), because an int goes from [-2^31, 2^31-1]. This is because the most left bit is representing the sign. So to fix that overflow, first interpret that sequence of 1 and 0 characters as a Long. A long will do because the maximum value for a long is 2^63-1. Then convert the long to an int. This is done by simply taking the lower 32 bits.


The bug in your code is that you didn't cast the Long.parseLong to an int. So this should work:

lat_bin = Integer.toBinaryString((int)(lat_dec * 1000000));   
lat_dec_conv =  ((int) Long.parseLong(lat_bin, 2)) / 1000000.0;
 public static void convertStringToDecimal(String binary) {
    int decimal = 0;

    int power = 0;

    if (binary.charAt(0) == '1' && binary.length() == 32) {

        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < binary.length(); i++) {

            builder.append((binary.charAt(i) == '1' ? '0' : '1'));

        }

        while (binary.length() > 0) {

            int temp = Integer
                    .parseInt(builder.charAt((binary.length()) - 1)+"");
            decimal += temp * Math.pow(2, power++);
            binary = binary.substring(0, binary.length() - 1);

        }

        System.out.println((decimal + 1) * (-1));

    } else {

        while (binary.length() > 0) {
            int temp = Integer
                    .parseInt(binary.charAt((binary.length()) - 1) + "");
            decimal += temp * Math.pow(2, power++);
            binary = binary.substring(0, binary.length() - 1);
        }

        System.out.println(decimal);

    }
}

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