【问题标题】:How produce two's complement of a Uint16?如何产生 Uint16 的二进制补码?
【发布时间】:2019-05-12 11:41:50
【问题描述】:

我有两个字节的数据。我将它们中的每一个都转换为 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 中,int 是 32 位的。你到底期待什么?
  • int 是 32 位的。你应该使用short
  • 简洁明了的措辞。

标签: java binary uint8t uint16


【解决方案1】:

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 

【讨论】:

    【解决方案2】:

    数字的“二进制补码”是通过取反获得的,至少在使用整数的二进制补码表示的机器上是这样,几乎所有现代硬件都是如此,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);
        }
    }
    

    mn 的上述输出相同。

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

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

    【讨论】:

      猜你喜欢
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多