How to find the number 1 in a binary number O (1) times?

I know this was asked before, but I am considering this particular solution, listed here :

int BitCount(unsigned int u)
{
     unsigned int uCount;

     uCount = u - ((u >> 1) & 033333333333) - ((u >> 2) & 011111111111);
     return ((uCount + (uCount >> 3)) & 030707070707) % 63;
}

How it works?

Are there any warnings?

Theoretically, you can find the answer in constant time? I mean, do we need to iterate over the bits to count?
+4
source share
4 answers

Bit count

An unsigned 32-bit integer ucan be written as follows:

u = a31 * 231 + a30 * 230 + ... + a0 * 20

We need a value .a31 + a30 + ... + a0

Compare the values u >> k:

u >> 0  = a31 * 231 + a30 * 230 + ... + a1 * 21 + a0 * 20
u >> 1  = a31 * 230 + a30 * 229 + ... + a1 * 20
u >> 2  = a31 * 229 + a30 * 228 + ...
...
u >> 29 = a31 * 22  + a29 * 21  + ...
u >> 30 = a31 * 21  + a30 * 20 
u >> 31 = a31 * 20 

:

u >> 0 - u >> 1 - u >> 2 - ... - u >> 31 = p

, :

  u >> 0 - u >> 1 - u >> 2 - ... - u >> 31
= u >> 0 - (u >> 1 + u >> 2 + ... + u >> 31)
= u - q

q? , u >> k . a31 :

  a31 * 230 + a31 * 229 + ...
= a31 * (230 + 229 + ...)
= a31 * (231 - 1)

a30:

  a30 * 229 + a30 * 228 + ...
= a30 * (229 + 228 + ...)
= a30 * (230 - 1)

: q = a31 * (231 - 1) + a30 * (230 - 1) + ...

, ,

u - q = a31 * 231 - a31 * (231 - 1) + ...
      = a31 + a30 + ... + a0

3-

, 3 :

u >> 0                = AaBbbCccDddEeeFffGggHhhIiiJjjKkk (each letter is a bit)
u >> 1 & 033333333333 =  A Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk (blank = zero)
u >> 2 & 011111111111 =     B  C  D  E  F  G  H  I  J  K

uCount , u.

uCount      =   αβγδεζηθικλ (each greek letter is an octet)
uCount >> 3 =    αβγδεζηθικ

, uCount + (uCount >> 3) (λ+κ) * 20 + (κ+ι) * 23 + (ι+θ) * 26 + ...

ANDing 0o30707070707 , :

r = (λ+κ) *  20 + (ι+θ) *  26 + (η+ζ) *  212 + ...
  = (λ+κ) * 640 + (ι+θ) * 641 + (η+ζ) * 642  + ...

-64, base-64, α+β+γ+δ+ε+ζ+η+θ+ι+κ+λ, . 64 : , 32, 63.

+8

, .

, , , O(1) (, 32).

+5

- popcnt. . , .

+5

, . 8-, 16-, 32-, 64-, 128- .. , , , .

When we say that this operation is O (1), we mean that it can be done in constant time regardless of the size of the word. When counting bits, the naive method is O (n) in the number of bits.

Practically speaking, this is only O (1), when the processor can work with the word size initially.

As for how it works, it uses "magic numbers." See this news table for an explanation .

+1
source

All Articles