如何产生Uint16的二进制补码?

时间:2019-05-12 11:41:51

标签: java binary uint8t 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 

2 个答案:

答案 0 :(得分:0)

Java不是使用位的最佳编程语言。但是,如果您愿意,可以阅读documentation来查看数字在Java中的表示方式;如何work with bytes,也可以进行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 

答案 1 :(得分:0)

至少在使用整数的二进制补码表示的机器上,通过求反获得数字的“二进制补码”,这几乎适用于所有现代硬件,对于Java虚拟机也是如此。

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

在二进制补码硬件和Java虚拟机中,取反等效于求反并加1。以下内容说明了这一点:

示例:

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;