我一般很难处理位和字节,但我有一个分配,我必须在那时屏蔽n个位,我不知道如何去做。假设我有二进制数1011010,我想要最重要的2位(10)。然后我想要接下来的2位(11),然后是接下来的2位,依此类推,直到所有位都被处理完毕。所以掩码首先是1100000,然后是0011000等。我知道我可以通过移动n个索引并减去1得到最低有效位,但是我该怎么做呢?
我有int mask =((1<<<  NUM_BIT)-1)*(NUM_BIT * 2);,其中NUM_BIT是我正在屏蔽的位数(当前为2)但这对字节无效超过4位,我不知道如何将1位向下移动......
答案 0 :(得分:0)
一种解决方案可能是这样的:
int i = 4; // number of bits you want to mask
int mask = ~((1 << 32 - i) - 1); // will return 11110000000000000000000000000000
然后你只是&#34;移动&#34;右边的位,直到mask
为0
。
示例:
while (mask != 0) {
String replace = String.format("%32s", Integer.toBinaryString(mask)).replace(' ', '0'); // just to be more clear
System.out.println(replace);
mask = mask >>> i;
}
输出:
11110000000000000000000000000000
00001111000000000000000000000000
00000000111100000000000000000000
00000000000011110000000000000000
00000000000000001111000000000000
00000000000000000000111100000000
00000000000000000000000011110000
00000000000000000000000000001111
00000000000000000000000000000000
如果您想要两位,只需将i
替换为2;
答案 1 :(得分:0)
示例代码:
public class TestMain {
public static void main(String[] args) {
int inputInt = Integer.parseInt("1011010", 2);
twoBits(inputInt);
}
public static void twoBits(int inputInt) {
int mask = 3<<30;
while(mask != 0 && (inputInt & mask)==0) {
mask >>>= 2;
}
System.out.println(String.format("%32s", Integer.toBinaryString(inputInt)).replace(' ', '0'));
do {
System.out.println(String.format("%32s", Integer.toBinaryString(inputInt & mask)).replace(' ', '0'));
mask >>>= 2;
}
while(mask != 0 && (inputInt & mask)!=0);
}
}
输出:
00000000000000000000000001011010
00000000000000000000000001000000
00000000000000000000000000010000
00000000000000000000000000001000
00000000000000000000000000000010