Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

bit

counting

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

If the int contains: 0b00000000000000000000000000001010

The number of transitions are: 4

If the int contains: 0b00000000000000000000000000001001

The number of transitions are: 3

Language is C.

like image 532
tormod Avatar asked Jan 23 '09 09:01

tormod


People also ask

How to count number of bits in an integer Java?

Java Integer bitCount() method The bitCount() method of Integer class of java. lang package returns the count of the number of one-bits in the two's complement binary representation of an int value. This function is sometimes referred to as the population count.

What are set bits?

Set bits in a binary number is represented by 1. Whenever we calculate the binary number of an integer value then it is formed as the combination of 0's and 1's. So, the digit 1 is known as set bit in the terms of the computer.


2 Answers

int numTransitions(int a)
{
  int b = a >> 1; // sign-extending shift properly counts bits at the ends
  int c = a ^ b;  // xor marks bits that are not the same as their neighbors on the left
  return CountBits(c); // count number of set bits in c
}

For an efficient implementation of CountBits see http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel

like image 181
Crashworks Avatar answered Sep 19 '22 12:09

Crashworks


Fastest depends on your scenario: As you specified your datatype as constant sized (unsigned int), it is possible with lookup table. But when you need this operation only once the constant overhead to init the table is too big, and scanning+counting through the int is far faster despite.

I guess the overall best would be a combination: Look up table for a byte or word (256 or 64k entries is not so much), and then combine the bytes/words by their last/first bit.

like image 42
flolo Avatar answered Sep 19 '22 12:09

flolo