Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

the general idea is:

  1. bitwise shift to the right
  2. xor with original value, so only transition bits are left
  3. count remaining bits


here's a demo implementation, using std::bitset (for demo purpose), same idea works with uints, too, ofc.

#include <bitset>
bitset<24> a("00001111100000111100000");
// 000001111100000111100000
auto b = a >> 1;
// 000000111110000011110000
auto c = a ^ b;
// 000001000010000100010000
auto len = c.count();  // popcnt() , if you use integers.
// 4