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 bi
A short answer.
long num = ~0L;
int cnt1 = Long.bitCount(num & (num >>> 1) & 0x5555555555555555L);
System.out.println(cnt1);
int cnt2 = 32 - cnt1;
prints
32
What you need to do is create a bit-mask and run it over your value, assuming this is homework I will only give some pointers:
long mask = 0x03L;
&
to check a value against a maskIf you put above hints into code, you will have your answer :-)
Edit now that the results are in, my solution would be:
long cnt1 = 0;
long cnt2 = 0;
for (long mask = 0x03; mask != 0; mask <<=2) {
(mask == (value & mask)) ? cnt1++ : cnt2++;
}
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
}