反转位后的32位总和,最终结果从二进制到十进制

时间:2015-01-24 03:33:54

标签: java for-loop int

如果我的输入是1.那么1作为二进制的32位是00000000000000000000000000000001.如果我反转这些位,它的1111111111111111111111111111111110。如果我将这个反转的位数从二进制转换为十进制,我应该得到4294967294.我写了以下内容程序要做到这一点,但我的最终总和是错误的,尽管我能够正确地反转位。我得到了-3。

这是我的代码:

public class FlippingBits {

public static void main(String[] args) {
    FlippingBits fpb = new FlippingBits();
    int i = 1;
    int index = 0;
    int[] bitArray = new int[32];
    fpb.convertToBin(i, bitArray, index);
}

private void convertToBin(int decimalInput, int[] unsigned32, int index) {
    if (decimalInput <= 1) {
        unsigned32[index++] = flipBit(decimalInput);
        for (int i = index; i < unsigned32.length; i++) {
            unsigned32[i] = 1;
        }
        printArray(unsigned32);
        System.out.println();
        sumBit(unsigned32);
        return;
    }
    int remainder = decimalInput % 2;
    unsigned32[index] = flipBit(remainder);
    index++;
    convertToBin(decimalInput >> 1, unsigned32, index);
}

private void sumBit(int[] unsigned32) {
    int sum = 0;
    for (int i = 0; i < unsigned32.length; i++) {
        sum += unsigned32[i] * (int) Math.pow(2, i);
    }
    System.out.println(sum);
}

private int flipBit(int remainder) {
    if (remainder == 1) {
        return 0;
    } else {
        return 1;
    }
}

private void printArray(int[] unsigned32) {
    for (int i = 0; i < unsigned32.length; i++) {
        System.out.print(unsigned32[i]);
    }
}

}

我不确定我的sumBit(int [])方法发生了什么。我很确定我没有忘记如何从二进制转换为十进制。

3 个答案:

答案 0 :(得分:1)

您实际上并未使用无符号整数。你的变量已经溢出。

答案 1 :(得分:1)

这应该有帮助

public class FlippingBits {

public static void main(String[] args) {
    FlippingBits fpb = new FlippingBits();
    int i = 1;
    int index = 0;
    int[] bitArray = new int[32];
    fpb.convertToBin(i, bitArray, index);
}

private void convertToBin(int decimalInput, int[] unsigned32, int index) {
    if (decimalInput <= 1) {
        unsigned32[index++] = flipBit(decimalInput);
        for (int i = index; i < unsigned32.length; i++) {
            unsigned32[i] = 1;
        }
        printArray(unsigned32);
        System.out.println();
        sumBit(unsigned32);
        return;
    }
    int remainder = decimalInput % 2;
    unsigned32[index] = flipBit(remainder);
    index++;
    convertToBin(decimalInput >> 1, unsigned32, index);
}

private void sumBit(int[] unsigned32) {
    long sum = 0;
    for (int i = unsigned32.length - 1; i >= 0; i--) {
        sum += unsigned32[i] * (int) Math.pow(2, i);
    }
    System.out.println(sum);
}

private int flipBit(int remainder) {
    if (remainder == 1) {
        return 0;
    } else {
        return 1;
    }
}

private void printArray(int[] unsigned32) {
    for (int i = unsigned32.length - 1; i >= 0; i--) {
        System.out.print(unsigned32[i]);
    }
}
}

答案 2 :(得分:1)

Java int数据类型是32位带符号的二进制补码,有关详细信息,请参阅http://www.cs.uwm.edu/~cs151/Bacon/Lecture/HTML/ch03s09.html