我目前正在学习逐位操作,我的任务是进行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位。
任何帮助让我理解这个问题将不胜感激!
如果我理解你,你想
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
许多1
s我们可以使用(1 << BITS_IN_INTEGER) - 1
。 - 1
将10000
转换为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)));
}