本文介绍了长位的Java位操作 - 计数设置和未设置位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的号码很长。现在我想要的是(以伪代码给出),
I have a long number. Now what I want is following (given in pseudo code) ,
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)
有人可以帮我怎么做吗?
Can anybody help me how to do that ?
推荐答案
你需要什么do是在每次迭代时向右移动2位,并使用数字3(二进制11)进行按位和(&)操作:
What you need to do is keep shifting by 2 bits to the right at every iteration and do a bitwise and (&) operation with the number 3 (11 in binary):
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
}
这篇关于长位的Java位操作 - 计数设置和未设置位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!