How to create mask with least significat bits set to 1 in C

前端 未结 6 1608
被撕碎了的回忆
被撕碎了的回忆 2021-02-13 06:43

Can someone please explain this function to me?

A mask with the least significant n bits set to 1.

Ex:

n = 6 --> 0x2F, n = 17 --> 0x1FFFF // I don\'t ge

6条回答
  •  渐次进展
    2021-02-13 07:03

    For both correctness and performance, the best way to accomplish this has changed since this question was asked back in 2012 due to the advent of BMI instructions in modern x86 processors, specifically BLSMSK.

    Here's a good way of approaching this problem, while retaining backwards compatibility with older processors.

    This method is correct, whereas the current top answers produce undefined behavior in edge cases.

    Clang and GCC, when allowed to optimize using BMI instructions, will condense gen_mask() to just two ops. With supporting hardware, be sure to add compiler flags for BMI instructions: -mbmi -mbmi2

    #include 
    #include 
    
    uint64_t gen_mask(const uint_fast8_t msb) {
      const uint64_t src = (uint64_t)1  << msb;
      return (src - 1) ^ src;
    }
    
    int main() {
      uint_fast8_t msb;
      for (msb = 0; msb < 64; ++msb) {
        printf("%016" PRIx64 "\n", gen_mask(msb));
      }
      return 0;
    }
    

提交回复
热议问题