Fastest way to count number of bit transitions in an unsigned int

前端 未结 6 2315
说谎
说谎 2021-02-09 20:31

I\'m looking for the fastest way of counting the number of bit transitions in an unsigned int.

If the int contains: 0b0000000000000000000000000000101

6条回答
  •  别跟我提以往
    2021-02-09 20:48

    Ok, with transitions you mean if you walk through the string of 0-s and 1-s, you count each occurance that a 0 follows a 1 or a 1 follows a 0.

    This is easy by shifting bits out and counting the changes:

    transitions(n)
      result = 0
      prev = n mod 2
      n = n div 2
      while n<>0 
        if n mod 2 <> prev then
          result++
          prev = n mod 2
        fi
        n = n div 2
      elihw
      return result
    

    you can replace the mod and div with shifts.

提交回复
热议问题