我的号码很长。现在我想要的是(伪代码中给出),
int cnt1 = 0
int cnt2 = 0
for each two bits of that long
if the two bits == 11
then cnt1++
else
cnt2++
Print i and i+1 th bits are ... (example 00, 11 etc.) and cnt1 = ... and cnt2 = ...
(for example if number is three (representation "00 00 00 .... 11)"
it will give output cnt1 = 1 and cnt2 = 31)
有人可以帮我怎么做吗?
答案 0 :(得分:3)
您需要做的是在每次迭代时向右移动2位,并使用数字3(二进制11)执行按位和(&)运算:
long number;
int cnt1 = 0;
int cnt2 = 0;
long test = 3;
int counter = 0;
while(counter < 64) { // we have 64 bits to inspect
if((number & test) == 3) { // last 2 bits are 11
cnt1++;
} else { // last 2 bits are either 10, 01 or 00
cnt2++;
}
counter += 2;
number = number >>> 2; // shift by 2 bits to the right
}
答案 1 :(得分:2)
你需要做的是创建一个位掩码并在你的值上运行它,假设这是作业,我只会给出一些指示:
long mask = 0x03L;
&
检查掩码值如果您将上述提示放入代码中,您将得到答案: - )
编辑现在结果出来了,我的解决方案是:
long cnt1 = 0;
long cnt2 = 0;
for (long mask = 0x03; mask != 0; mask <<=2) {
(mask == (value & mask)) ? cnt1++ : cnt2++;
}
答案 2 :(得分:2)
一个简短的回答。
long num = ~0L;
int cnt1 = Long.bitCount(num & (num >>> 1) & 0x5555555555555555L);
System.out.println(cnt1);
int cnt2 = 32 - cnt1;
打印
32