Maybe you can help me with the following problem that can help me speed a memory manager I am thinking of (I am not sure a solution exists – I did not find one).
I have a 32 bits register and I need to find if there are n consecutive set bits in it, and if so what is their offset. For example if the register holds the following value 111100000000000000000001111111000 and n equals to 4 – any of the following answer is accepted (offsets starts from 0):
3, 4, 5, 6, 28
The atomic operations I have are all the regular bitwise operations (&, |, ~, …) and also finding the least significant bit offset (3 in the register above). The algorithm (assuming one exists) – should take no more than 5 atomic operations.
for every possible byte value (0-255) calculate the number of bits at the beginning, the number of bits at the end and the longest number of consecutive bits inside the byte and the offset of this sequence. For instance, for
0b11011101, there are 2 bits at the beginning, 1 bit at the end and a sequence of 3 consecutive bits in it.Store this values in 4 arrays, for instance
start,end,longest,longest_offset.Then, consider the 32bit number as a 4 bytes array and iterate over these bytes as follows:
update: notice that the endianess of your CPU may require changing the loop direction.