Java converting negative binary back to integer

允我心安 提交于 2019-12-11 04:44:19

问题


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


回答1:


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;



回答2:


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

    }
}


来源:https://stackoverflow.com/questions/14012013/java-converting-negative-binary-back-to-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!