Determine which single bit in the byte is set

后端 未结 8 991
臣服心动
臣服心动 2020-12-03 18:53

I have a byte I\'m using for bitflags. I know that one and only one bit in the byte is set at any give time.

Ex:

8条回答
  •  不知归路
    2020-12-03 19:31

    Easiest thing is to create a lookup table. The simplest one will be sparse (having 256 elements) but it would technically avoid iteration.

    This comment here technically avoids iteration, but who are we kidding, it is still doing the same number of checks: How to write log base(2) in c/c++

    Closed form would be log2(), a la, log2() + 1 But I'm not sure how efficient that is - possibly the CPU has an instruction for taking base 2 logrithms?

提交回复
热议问题