如何产生 Uint16 的补码?

How produce two's complement of a Uint16?

我有两个字节的数据。我将它们中的每一个都转换为 Uint8,然后从中生成了一个 Uint16。

如何生成此 Uint16 数字的二进制补码?

我试过 uInt16 = ~uInt16 + 1 但代码生成 32 位整数,我希望它保持 16 位整数。

    byte firstByte, secondByte;
    int firstUint8, secondUint8, uInt16;
    firstByte = buffer[index];//get first byte from buffer
    secondByte = buffer[index + 1];//get second byte from buffer


    firstUint8=firstByte & 0xFF;//produce Uint8
    secondUint8 = secondByte & 0xFF;//produce Uint8

    uInt16 = 256 * firstUint8 + secondUint8;//create Uint16 from these to    Uint8

    twosComplementOfUInt16=~number+1; //produce 32 bit integer but I want int16 

Java 不是处理位的最佳编程语言。但如果你愿意,你可以阅读 documentation to see how the number are represented in java; how to work with bytes or you can do a tutorial.

作为观察 (~ and +) returns an integer

    public static void main(String[] args) {
        int uint8 = 0xff;
        int uint16 = 0xffff;
        long uint32 = 0xffffffff;

        int one = 0x0001;
        int ten = 0x000A;
        int twoComplementOfTen = 0xFFF6;
        int computedTwoComplementOfTen = ~ten + one;
        int revertTwoComplementOfTen = ~twoComplementOfTen + one;

        System.out.printf("One = 0x%04X \n", one);
        System.out.printf("ten = 0x%04X \n", ten);
        System.out.printf("~ten + one = 0x%04X \n", twoComplementOfTen);
        System.out.printf("Computed ~ten + one = 0x%04X \n", computedTwoComplementOfTen);
        System.out.printf("~twoComplementOfTen + one = 0x%04X \n", revertTwoComplementOfTen);

        System.out.printf("Computed ~ten + one with uint16 mask = 0x%04X \n", uint16 & computedTwoComplementOfTen);
        System.out.printf("~twoComplementOfTen + one with uint16 mask  = 0x%04X \n", uint16 & revertTwoComplementOfTen);
    }
Output:

One = 0x0001 
Ten = 0x000A 
~ten + one = 0xFFF6 
Computed ~ten + one = 0xFFFFFFF6 
~twoComplementOfTen + one = 0xFFFF000A 
Computed ~ten + one with uint16 mask = 0xFFF6 
~twoComplementOfTen + one with uint16 mask  = 0x000A 

数字的 "twos complement" 是通过取反获得的,至少在使用 twos-complement 表示整数的机器上是这样,这对几乎所有现代硬件都是正确的,对 Java 虚拟机.

  short x;
     ...set value of x...
  x = -x; 

在twos-complement硬件和Java虚拟机中,取反等价于取反加一。以下证明了这一点:

示例:

public class Foo {
    public static void main(String[] args) {
        short n = 2; n = -n;
        System.out.println(n);
        short m = 2; m = ~m + 1;
        System.out.println(m);
    }
}

上面的输出对于 mn 是相同的。

如果您发现有必要使用 32 位整数作为值,那么您可以简单地将结果屏蔽为 16 位。

    int uint16 = some_value;
    int compl = -uint16 & 0xffff;