位取反后的32位之和,最终结果由二进制转为十进制

Sum of 32 bits after inverting bits, final result going from binary to decimal

如果我的输入是 1。那么 1 作为二进制的 32 位是 000000000000000000000000000000001。如果我反转这些位,它是 11111111111111111111111111111110。如果我将这个反转的位数从二进制转换为十进制,我应该得到 42949I67294以下程序可以执行此操作,但尽管我能够正确反转位,但我的最终总和是错误的。我得到-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[]) 方法发生了什么。我很确定我没有忘记如何将二进制转换为十进制。

您实际上并没有使用无符号整数。你的变量溢出了。

这应该有帮助

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

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