如何在 Java 中创建 32 位掩码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19887034/
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
How to create 32 bit mask in Java
提问by uohzxela
So far I have this code to create 16 bit mask. However I do not know how to create a 32 bit mask using this approach. Any ideas?
到目前为止,我有这段代码来创建 16 位掩码。但是我不知道如何使用这种方法创建 32 位掩码。有任何想法吗?
edit: I want to create 32 masks of 32 bits, each with with its respective bit being 1 and the rest of the bits being zero. For example: mask 1 has the leftmost bit being 1 while the rest of the bits are zero, mask 2 has the 2nd leftmost bit being 1 while the rest of the bits are zero. I dunno how to explain more succinctly but I hope you guys get the idea...
编辑:我想创建 32 个 32 位掩码,每个掩码各自的位为 1,其余位为零。例如:掩码 1 的最左边的位为 1 而其余位为零,掩码 2 的第二个最左边的位为 1 而其余位为零。我不知道如何更简洁地解释,但我希望你们明白...
mask = new int[16];
mask[0] = 0x8000;
mask[1] = 0x4000;
mask[2] = 0x2000;
mask[3] = 0x1000;
mask[4] = 0x0800;
mask[5] = 0x0400;
mask[6] = 0x0200;
mask[7] = 0x0100;
mask[8] = 0x0080;
mask[9] = 0x0040;
mask[10] = 0x0020;
mask[11] = 0x0010;
mask[12] = 0x0008;
mask[13] = 0x0004;
mask[14] = 0x0002;
mask[15] = 0x0001
采纳答案by Stephen C
Here's how to create a 32 bit mask in Java.
这是在 Java 中创建 32 位掩码的方法。
int mask = 0x00010000; // for example.
And if you want to create a 32 bit mask with bit N set then
如果你想创建一个设置了位 N 的 32 位掩码,那么
int mask = 1 << N; // Assumes the rightmost bit is numbered zero ...
And if you want to create an array of masks, then just do the above in a loop, in the obvious fashion.
如果你想创建一个掩码数组,那么只需以明显的方式在循环中执行上述操作。
int[] masks = new int[32];
for (int n = 0; n < 32; n++) {
masks[n] = 1 << n;
}
In reality, your supposed "16 bit masks" are also 32 bit masks, because int
is a 32 bit type in Java.
实际上,您假设的“16 位掩码”也是 32 位掩码,因为int
是 Java 中的 32 位类型。
And like @Matt Ball, I'm puzzled as to what you are really trying to do, and whether you are going about it is a sensible way to achieve it. Why do you need an array of masks when you can create a mask on the fly with less code?
和@Matt Ball 一样,我对您真正想做的事情感到困惑,以及您是否打算这样做是实现它的明智方法。当您可以用更少的代码即时创建掩码时,为什么需要一组掩码?
回答by Syd Kerckhove
I think you are doing well.
我认为你做得很好。
AMOUNT_OF_BITS = 32;
mask = new long[AMOUNT_OF_BITS];
for (long i = 0; i < AMOUNT_OF_BITS; i++)
{
mask[i] = Math.pow(2,i);
}
This should work, I think.
这应该有效,我想。