-1

我有两个字节的数据。我将它们中的每一个都转换为 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 
4

2 回答 2

0

Java 不是使用位的最佳编程语言。但是,如果您愿意,可以阅读文档以了解数字在 java 中的表示方式;如何使用字节或者你可以做一个教程

作为观察,(〜和+)返回一个整数

    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 
于 2019-05-12T13:14:49.063 回答
0

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

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

在二进制补码硬件和 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);
    }
}

上面的输出对于m和是相同的n

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

    int uint16 = some_value;
    int compl = -uint16 & 0xffff;
于 2019-05-12T19:00:28.703 回答