Determine which single bit in the byte is set

后端 未结 8 986
臣服心动
臣服心动 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:38

    unsigned getSetBitLocation(unsigned char b) {
      unsigned pos=0;
      pos = (b & 0xf0) ? 4 : 0; b |= b >>4;
      pos += (b & 0xc) ? 2 : 0; b |= b >>2;
      pos += (b & 0x2) ? 1 : 0; 
      return pos; 
    }
    

    It would be hard to do it jumpfree. Maybe with the Bruin sequences ?

提交回复
热议问题