java 从 Int 中获取 n 个最低有效位
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12766590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get n Least Significant Bits from an Int
提问by Wingdom
This seems fairly straightforward, but I cant find an answer. If I have an int X, what is the best way to get N least significant bits from this int, in Java?
这看起来相当简单,但我找不到答案。如果我有一个 int X,那么在 Java 中从这个 int 中获取 N 个最低有效位的最佳方法是什么?
回答by Ted Hopp
This should work for all non-negative N < 3332:
这应该适用于所有非负 N < 3332:
x & ((1 << N) - 1)
It's worth elaborating on how this works for N == 31
and . For N == 32
N == 31
, we get 1 << N == Integer.MIN_VALUE
. When you subtract 1 from that, Java silently wraps around to Integer.MAX_VALUE
, which is exactly what you need. For N == 32
, the 1 bit is shifted completely out, so 1 << N == 0
; then (1 << N) - 1 == -1
, which is all 32 bits set.
值得详细说明这对N == 31
和 的作用。对于N == 32
N == 31
,我们得到1 << N == Integer.MIN_VALUE
。当您从中减去 1 时,Java 会默默地环绕到Integer.MAX_VALUE
,这正是您所需要的。对于N == 32
,1 位被完全移出,所以1 << N == 0
; then (1 << N) - 1 == -1
,这是所有 32 位设置。
For N == 32
, this unfortunately doesn't work because (thanks, @zstring!) the <<
operator only shifts by the right side mod 32. Instead, if you want to avoid testing for that case specially, you could use:
对于N == 32
,不幸的是这不起作用,因为(谢谢,@zstring!)<<
操作员只在右侧 mod 32 处移动。相反,如果您想避免专门针对这种情况进行测试,您可以使用:
x & ((int)(1L << N) - 1)
By shifting a long
, you get the full 32-bit shift, which, after casting back to an int
, gets you 0. Subtracting 1 gives you -1 and x & -1
is just x
for any int
value x
(and x
is the value of the lower 32 bits of x
).
通过移动 a long
,您可以获得完整的 32 位移位,在转换回 an 之后int
,得到 0。减去 1 得到 -1,x & -1
并且仅x
适用于任何int
值x
(并且x
是 的低 32 位的值x
)。
回答by Peter Lawrey
Ted's approach is likely to be faster but here is another approach
Ted 的方法可能更快,但这是另一种方法
x << -N >>> -N
This shift all the bit up and then down to chop off the top bits.
这将所有位向上然后向下移动以切掉最高位。
int i = -1;
System.out.println(Integer.toBinaryString(i));
i = i << -5 >>> -5;
System.out.println(Integer.toBinaryString(i));
prints
印刷
11111111111111111111111111111111
11111
回答by user12042
You can also use a mask. If you use the & bitwise operator you can then remove whatever bit you would want to remove (say the highest x bits);
您也可以使用面膜。如果您使用 & 按位运算符,则可以删除您想要删除的任何位(例如最高的 x 位);
int mask = 0x7FFFFFFF //Example mask where you will remove the
// most significant bit
// (0x7 = 0111b and 0xF = 1111b).
int result = numberToProcess & mask; //And apply the mask with the &bitwise op.
The disadvantage to this is that you will need to make a mask for each bit, so perhaps this is better seen as another method of approach in general.
这样做的缺点是您需要为每个位制作一个掩码,因此通常将其视为另一种方法更好。