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

前端 未结 5 1043
抹茶落季
抹茶落季 2020-11-29 08:57

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
5条回答
  •  青春惊慌失措
    2020-11-29 09:36

    Quoting from http://graphics.stanford.edu/~seander/bithacks.html

    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.

提交回复
热议问题