Search code examples
bit-manipulationbit-fields

Index of bits in 8-Bit variable


I have an 8-Bit variable and I want to get the index of each 1-Bit.

For 00000011 the indices would only be 1 and 2. To get the indices I would use a simple for loop and check whether a bit is 1- at a given position.

My approach will always need 8-iterations. Can this be done more efficiently?


Solution

  • Not sure it would accelerate your issue but you could shift your 8 bit variable (if its unsigned) at every iteration and test if the value is zero for early loop exit