- 1

How to count set bit pairs in supplied integer?

6th Apr 2020, 10:49 AM
RUSHIKESH S.
RUSHIKESH S. - avatar
4 ответов
+ 3
RUSHIKESH S. it looks like this question was never solved. I think enough time has passed that I may supply a solution. If you shift the bits leftward by one position then bitwise & with the original number you will get a result that has 1 bit set for every original pair. Count the number of 1 bits and that will be the final answer. Check out my implementation: #include <stdio.h> //Brian Kernighan's favorite bit counter unsigned int countBits(unsigned int v) { unsigned int c; for (c = 0; v; c++) v &= v - 1; return c; } //count pairs of adjacent 1 bits int main() { unsigned int n; scanf("%u", &n); //here is the magic! printf("%u\n", countBits(n&n<<1)); return 0; }
11th Jan 2021, 10:38 AM
Brian
Brian - avatar
0
Set bit pairs? you mean adjacent set bits or what?
7th Apr 2020, 12:24 PM
Ipang
0
Yes
7th Apr 2020, 12:25 PM
RUSHIKESH S.
RUSHIKESH S. - avatar
0
Have you tried? How far have you gone through with this? Or is it solved?
7th Apr 2020, 12:35 PM
Ipang