开发者

Fastest ways to set and get a bit

I'm just trying to develop ultra-fast functions for setting and getting bits in uint32 arrays. For example, you can say "set bit 1035 to 1". Then, the uint32 indexed with 1035 / 32 is used with the bitposition 1035 % 32. I especially don't like the branching in the setbit function.

Here is my approach:

void SetBit(uint32* data, const uint32 bitpos, const bool newval)
{
   if (newval)
   {
      //Set On
      data[bitpos >> 5u] |= (1u << (31u - (bitpos & 31u)));
      return;
   }
   else
   {
      //Set Off
      data[bitpos >> 5u] &= ~(1u << (31u - (bitpos & 31u)));
      return;
   }
}

and

bool G开发者_高级运维etBit(const uint32* data, const uint32 bitpos)
{
   return (data[bitpos >> 5u] >> (31u - (bitpos & 31u))) & 1u;
}

Thank you!


First, I would drop the 31u - ... from all expressions: all it does is reordering the bits in your private representation of the bit set, so you can flip this order without anyone noticing.

Second, you can get rid of the branch by using a clever bit hack:

void SetBit(uint32* data, const uint32 bitpos, const bool f)
{
    uint32 &w = data[bitpos >> 5u];
    uint32 m = 1u << (bitpos & 31u);
    w = (w & ~m) | (-f & m);
}

Third, you can simplify your getter by letting the compiler do the conversion:

bool GetBit(const uint32* data, const uint32 bitpos)
{
    return data[bitpos >> 5u] & (1u << (bitpos & 31u));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜