Determine which single bit in the byte is set

后端 未结 8 929
臣服心动
臣服心动 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 ?

    0 讨论(0)
  • 2020-12-03 19:41

    if you define

    const char bytes[]={1,2,4,8,16,32,64,128}
    

    and use

    struct byte{
    char data;
    int pos;
    }
    void assign(struct byte b,int i){
    
    b.data=bytes[i];
    b.pos=i
    }
    

    you don't need to determine the position of the set bit

    0 讨论(0)
提交回复
热议问题