## Efficient bitwise operations for counting bits or find the right|left most ones

Related searches

Given an unsigned int, I have to implement the following operations :

1. Count the number of bits set to 1
2. Find the index of the left-most 1 bit
3. Find the index of the righ-most 1 bit

(the operation should not be architecture dependents).

I've done this using bitwise shift, but I have to iterate through almost all the bits(es.32) . For example, counting 1's:

```unsigned int number= ...;
while(number != 0){
if ((number & 0x01) != 0)
++count;
number >>=1;
}
```

The others operation are similar.

So my question is: is there any faster way to do that?

Count set bits in an integer, Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program. C++; C; Java� We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand

Take a look at ffs(3), ffsl(3), fls(3), flsl(3).

The ffs() and ffsl() functions find the first bit set (beginning with the least significant bit) in i and return the index of that bit.

The fls() and flsl() functions find the last bit set in i and return the index of that bit.

You might be interested in bitstring(3), too.

Position of rightmost set bit, Write a one line function to return position of first 1 from right to left, Left shift m by one till we find the first set bit, as the first set bit gives a� However, we can make this much more space-efficient by using bitwise operators. Since each coordinate is at most 1000, that means we only need 10 bits to store each number, since binary 1111111111

The best method for counting bits in a 32-bit integer v is the following:

```unsigned int v; // count bits set in this (32-bit value)
unsigned int c; // store the total here
v = v - ((v >> 1) & 0x55555555);                    // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);     // temp
c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
```

The best bit counting method takes only 12 operations, which is the same as the lookup-table method, but avoids the memory and potential cache misses of a table. It is a hybrid between the purely parallel method above and the earlier methods using multiplies (in the section on counting bits with 64-bit instructions), though it doesn't use 64-bit instructions. The counts of bits set in the bytes is done in parallel, and the sum total of the bits set in the bytes is computed by multiplying by 0x1010101 and shifting right 24 bits.

Bit Manipulation, Left shift is equivalent to multiplying the bit pattern with 2k ( if we are shifting k bits ). Note: All left and right side taken in this article, are taken with reference to the 2) Count the number of ones in the binary representation of the given number. 5) Find the largest power of 2 (most significant bit in binary form), which is� Bitwise right shift: Shifts the bits of the number to the right and fills 0 on voids left as a result. Similar effect as of dividing the number with some power of two. Example: Example 1: a = 10 a >> 1 = 5 Example 2: a = -10 a >> 1 = -5 Bitwise left shift: Shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two.

"The righ-most 1 bit" of number x is given by

```pos(1st '1') = log_2(x XOR (x-1) + 1) - 1
```

E.g.:

```x               = 1100101000;
x-1             = 1100100111;
x XOR (x-1)     = 0000001111;
x XOR (x-1) + 1 = 0000010000;
```

The base2-log of the last line then gives you the correct position + 1. So substract 1 from the log-result and you'll have the most-right '1' bit.

For the most-right '0' bit you may use

```pos(1st '0') = log_2(x XOR (x+1) + 1) - 1
```

Bitwise operators — Facts and Hacks, The output of bitwise OR is 1 if at least one corresponding bit of two The bitwise XOR operator is the most useful operator from technical find the odd occurring number” This problem can be efficiently solved by just These are simply the left and right shifts discussed earlier Count set bits in integer: So if we subtract a number by 1 and do bitwise & with itself (n & (n-1)), we unset the rightmost set bit. If we do n & (n-1) in a loop and count the no of times loop executes we get the set bit count. The beauty of this solution is the number of times it loops is equal to the number of set bits in a given integer.

Bit Twiddling Hacks, Testing for ranges of bytes in a word (and counting occurances found) This is one operation faster than the obvious way, sign = -(v < 0). because when signed integers are shifted right, the value of the far left bit is copied to the other bits. This method requires a 64-bit CPU with fast modulus division to be efficient. This is known as the Hamming weight of an integer. The simple, readable solution uses the bitwise right shift (>>) and bitwise AND (&). Remember that ANDing an integer with 1 tells us whether the least significant bit is set. Combining that fact with the right shift, the O (n) solution is

In other words if we start at the most significant bit and proceed to the right, counting the number of bits set to 1 until we reach the desired rank, r, then the position where we stop is returned. If the rank requested exceeds the count of bits set, then 64 is returned. The code may be modified for 32-bit or counting from the right.

If n has an alternate pattern, then n ^ (n >> 1) operation will produce a number having set bits only. ‘^’ is a bitwise XOR operation. That covered most of the application of Bitwise operators.

##### Comments
• Consider getting a copy of 'Hackers Delight', which is full of discussion of such low-level operations.
• Also: graphics.stanford.edu/~seander/bithacks.html
• thanks for the link..very intersting..
• Very efficient if there are just a few bits set Brian Kernighan's method
• This is not platform independent.