Bit operations to count longest string of 1s in a binary number - connections to FFT?

158 Views Asked by At

I found this rather applied question on another forum. How to calculate size of largest string of consecutive 1s in a binary number. However the other forum had neither much of a focus on applied mathematics nor computational efficiency.

Two examples of this operation, the binary number with longest sub-string of ones colored $\color{red}{\text{red}}$:

$$0000110011001100{\color{red}{1111}}0110{\color{red}{1111}}0000 \to 4$$ $$000011001100110011010110{\color{red}{11111}}000 \to 5$$


I came up with a solution which was based on xor of bit-shifts: $\text{xor}(a<<1,a)$. This operation gives 1 at each position a run of 1 or 0 turns into a run of 0 or 1. Then we can mask by bit-wise and:ing with the number and it's bit-wise inverse to have the 1s mark "start" and "ends" of these runs.

$$\begin{array}{c}000111110000111100000\\001111100001111000000\end{array} \underset{xor}{\to}00100001000100010000$$ so the xor result marks the start and end of each run of ones, which is a start and which is an end we can get from and:ing with $a$ or $not(a)$. Then we can get run-lengths by subtracting the pairwise leftmost set bit positions in these two numbers, setting the bit to 0 and iterating. Turns out there exist hardware-implemented "find first set bit" operations in many CPUs nowadays.


Anyway, back to the mathematics. We can view the xor-operation above as a convolution with $[1,-1]$ on a vector of elements from the field $\mathbb{Z}_2$, which on a less discrete field would have been a very popular basic differential approximator. Now on same less-discrete fields it is common to do convolutions in the Fourier domain by using the convolution theorem. Is it possible to do something similar on the bit representation of a binary number? We can do elementwise multiplication and addition (bitwise and, xor) and integral ("population count"), but how can one do Fourier Transforms and similar stuff on these things, and do the computational properties carry over to finite fields?