Creating a mask with N least significant bits set

前端 未结 6 1704
离开以前
离开以前 2021-01-18 01:00

I would like to create a macro or function1 mask(n) which given a number n returns an unsigned integer with its n least sig

6条回答
  •  梦毁少年i
    2021-01-18 01:09

    Here's one that is portable and conditional-free:

    unsigned long long mask(unsigned n)
    {
        assert (n <= sizeof(unsigned long long) * CHAR_BIT);
        return (1ULL << (n/2) << (n-(n/2))) - 1;
    }
    

提交回复
热议问题