Fast way to remove bits from a ulong

后端 未结 3 2074
太阳男子
太阳男子 2021-01-21 14:09

I want to remove bits from a 64 bit string (represented by a unsigned long). I could do this with a sequence of mask and shift operations, or iterate over each bit as in the cod

3条回答
  •  日久生厌
    2021-01-21 14:46

    There is a very good site that has been around for a long time called Bit Twiddling Hacks. It has a number of fast algorithms for bit manipulation. One you might want to look at (and I am copying verbatim here, this is not my own work) is this algorithm:

    Conditionally set or clear bits without branching

    bool f;         // conditional flag
    unsigned int m; // the bit mask
    unsigned int w; // the word to modify:  if (f) w |= m; else w &= ~m; 
    
    w ^= (-f ^ w) & m;
    
    // OR, for superscalar CPUs:
    w = (w & ~m) | (-f & m);
    

    On some architectures, the lack of branching can more than make up for what appears to be twice as many operations. For instance, informal speed tests on an AMD Athlon™ XP 2100+ indicated it was 5-10% faster. An Intel Core 2 Duo ran the superscalar version about 16% faster than the first. Glenn Slayden informed me of the first expression on December 11, 2003. Marco Yu shared the superscalar version with me on April 3, 2007 and alerted me to a typo 2 days later.

提交回复
热议问题