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

前端 未结 6 1927
隐瞒了意图╮
隐瞒了意图╮ 2021-02-13 06:42

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:15

    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;
    }
    

提交回复
热议问题