比特循环移位

问题描述 投票:0回答:1

我目前正在学习逐位操作,我的任务是进行4位整数的左旋转。

我的左旋转4bit的代码是

private static int BITS_IN_INTEGER = 4;

private static int leftRotate(int x, int n) {
  return (x << n) | (x >> (BITS_IN_INTEGER - n));
}

我希望在旋转后进行4位循环移位以保持4位,但似乎无法理解它是如何工作的。

示例:10(1010)左旋后1位将给出5(0101),但它给出的值为21,超过了我的4位。

任何帮助让我理解这个问题将不胜感激!

java bitwise-operators bit
1个回答
3
投票

如果我理解你,你想

  • 使用BITS_IN_INTEGER模拟整数而不是32位。
  • 对这样的模拟整数进行旋转

目前你可以进行旋转,但是实际int的高位不是模拟int的一部分,最终可以用0以外的其他值。示例:

intput x
0000 0000  0000 0000  0000 0000  0000 1100
                                     |____|___, emulated int
result of rotating left by n=2       |    |
0000 0000  0000 0000  0000 0000  0011 0011

我们可以看到,我们所要做的就是将模拟int(即32 - BITS_IN_INTEGER高位)上方的位设置为零。为此,我们使用逻辑“和”(&)。我们需要一个掩码,在我们想要设置为零的位上有0(任何& 0总是0)和我们想要保留的位上的1(任何& 1总是任何东西)。

  0...0  0011 0011  ←  the result from before
& 0...0  0000 1111  ←  a mask
——————————————————
  0...0  0000 0011  ←  the masked result where unused bits are 0

要生成0...01...1形式的掩码与BITS_IN_INTEGER许多1s我们可以使用(1 << BITS_IN_INTEGER) - 1- 110000转换为01111

static int BITS_IN_INTEGER = 4;
static int INTEGER_MASK = (1 << BITS_IN_INTEGER) - 1;

static int leftRotate(int x, int n) {
  return INTEGER_MASK & ((x << n) | (x >>> (BITS_IN_INTEGER - n)));
}
© www.soinside.com 2019 - 2024. All rights reserved.