左移一个特定的编号。的 1s 具体编号次

Left shift a specific no. of 1s specific no. of times

我想左移一个特定的编号。其中一个具体编号。次。我正在尝试这样的事情

//Left shift 3 1's by 5. 
int a = 0; 
a = 0b(111 << 5) ;  //Error : unable to find numeric literal
                    // operator 'operator""b'        
std::cout << a; //Should be 224

关于如何解决上述问题有什么建议吗?理想情况下,我想要这样的东西

int a = 0;
int noOfOnes = 3;
a = 0b(noOfOnes << 5);

我不确定如何在 C++ 中完成上述操作?

很简单((1u << a) - 1u) << b,其中a1的个数,b是偏移量


示例:

#include <iostream>
#include <bitset>

unsigned foo(unsigned size, unsigned offset)
{
    return ((1u << size) - 1u) << offset;
}

int main()
{
    unsigned x = foo(5, 3);
    std::cout << std::bitset<16>(x); // 0000000011111000
}

Try it live


如果a (or b) >= sizeof(unsigned) * CHAR_BIT(感谢@Deduplicator)

,此方法将失效

如果切换到最大的可用整数类型后仍然有问题,您可以添加一些安全检查:

#include <iostream>
#include <bitset>
#include <climits>

unsigned foo(unsigned size, unsigned offset)
{
    unsigned x = 0; 
    if (offset >= sizeof x * CHAR_BIT)
        return 0;
    if (size < sizeof x * CHAR_BIT)
        x = 1u << size;
    return (x - 1u) << offset;
}

int main()
{
    unsigned x = foo(32, 3);
    std::cout << std::bitset<32>(x);
}