'Find sum of bits of a char [closed]
I need a queue of size about 8 booleans. Every push should destroy an item from the tail. This can be achieved by a char in the resource limited application.
However I only care about the sum of those "flags", not their individual status. How can I find the sum of the set bits of an 8 bit char?
Solution 1:[1]
I come up with two methods.
A method is using a varible to count the sum, whenever you push, you maintain the varible, the change of the varible depends on what you push and what will pop.
Another method is an algorithm called "lowbit"
int lowbit(int x) {
return x & -x;
}
it will return the last 1 int the binary representation of the x.
So this can get the number of '1' in the binary representation of x.
for example, code like this.
int sum_of_1(int x) {
int res = 0;
while (x != 0) res++, x -= lowbit(x);
return res;
}
Solution 2:[2]
Counting bits set, Brian Kernighan's way
// count the number of bits set in v
unsigned char sum( unsigned char v )
{
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
v &= v - 1; // clear the least significant bit set
}
return v;
}
unsigned char push( unsigned char v, bool in )
{
v << 1;
if( in )
{
v |= 1;
}
return v;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | robotkkk |
| Solution 2 | Kethan Tellis |
