位级操作,从short值中获取位

Bit level operations, get a bit from a short value

我正在尝试从此输入 5 中获得以下结果 00000000000000101

这是我的代码,但没有意义:

public static int get16Bits(int x)
    {
        System.out.println((x & 0xffff) - ((x & 0x8000) << 1));
        return (x & 0xffff) - ((x & 0x8000) << 1);

    }

如何得到整数值的16位

尝试稍微更改一下您的 return 语句:

    public static String get16Bits(int x)
    {
        return (String.format("%016d", Integer.parseInt(Integer.toBinaryString(x))));

    }

这应该对你有帮助。

试试下面的方法:

String.format("%16s", Integer.toBinaryString(5)).replace(' ', '0')

第一部分不言自明:使用 & 0xffff 掩码删除高 16 位。

减去(x & 0x8000) << 1是在32位结果中保留16位数字正确符号的技巧:例如,0xffff,16位表示中的-1,转换为 0xffffffff,在 32 位表示中也是 -1。这比使用条件更好,因为它是无分支的。

您可以使用的另一个技巧是

(((x & 0xFFFF) << 16) >> 16)

这让16位数字的符号位"touch"成为32位数字的符号位,让右移对结果进行符号扩展

注意:如果您正在寻找数字的二进制 String 表示,则只需要 x & 0xffff 掩码,因为高 16 位是无论如何从字符串结果中删除。 This Q&A 解释了如何获得具有适当数目的前导零的整数的二进制表示。

我们可以试试下面这段代码,我们将使用 for 循环 :

public void getBits(int number){

      String bits = "";
      for (int i = 0; i < 16; i++) {
          bits = (number & 1) + bits;
          number >>= 1;
      }
      System.out.println("The bits are " + bits);
  }