【问题标题】:Left shift a specific no. of 1s specific no. of times左移一个特定的号码。 1s 具体编号次
【发布时间】:2026-02-13 09:05:02
【问题描述】:

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

//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++ 中完成上述操作?

【问题讨论】:

  • 以前知道吗?
  • @Deduplicator 我知道运行时需要多少个 1
  • 为什么会有一个随机的0b,而不是整数文字的一部分?

标签: c++ c++11 bit-manipulation bit-shift bitmask


【解决方案1】:

就像((1u &lt;&lt; a) - 1u) &lt;&lt; b 一样简单,其中a1s 的数量,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) &gt;= 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);
}

【讨论】:

    最近更新 更多