[Solved] how to count number of bit transitions in an unsigned int with java


The direct approach to this problem is to count the number of places where bit at the position i is different from bit at the position i+1. This can be done by XOR-ing the number with itself after a single right shift with sign extension:

Integer.bitCount(n ^ (n >> 1))

XOR operator ^ will put ones in all positions where bits at consecutive positions are different from each other. Integer.bitCount will complete the task by counting the number of ones.

Sign extension will ensure that there is no “phantom” transition from the most significant bit to zero, in cases when n is negative.

Demo.

solved how to count number of bit transitions in an unsigned int with java