Bit counting and geometric series
veitner.bearblog.dev·8h
Flag this post
  • 06 Nov, 2025 *

In this blogpost we make a connection between the operation of bit counting and a nice properties of unsigned binary numbers.

An identity

Consider x to be an unsigned strictly positive number. Let j be the first entry of our binary number that is unequal to 0, i.e. we can write it in binary notation as x=xn−1...xj+110...0.

Consider

x−1=∑j≤i≤n−1xi2i−1=2j+∑j<i≤n−1xi2i−1

We have the geometric series:

∑i∈{0,...,j−1}2i=1−2j1−2=2j−1

Rearranging the terms yields:

2j−1=∑i∈{0,...,j−1}2i

Plugging that into above equation we obtain:

x−1=∑i∈{0,...,n−1}yi2i

where yi=1 for i<j , yj=0 and yi=xi else, i.e. we can write as binary number x−1=xn−1...xj+101...1.

If we perform an bitwise AND of this number with x we will obtain

x∧x−1=xn−…

Similar Posts

Loading similar posts...