Raj*_*war 2 c++ bit-manipulation bitmask bit-shift c++11
我想留下一个特定的号码.具体的没有.时间.我正在尝试这样的事情
//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
Run Code Online (Sandbox Code Playgroud)
关于如何解决上述问题的任何建议?理想情况下,我想要这样的东西
int a = 0;
int noOfOnes = 3;
a = 0b(noOfOnes << 5);
Run Code Online (Sandbox Code Playgroud)
我不确定如何在C++中完成上述操作?
它很简单((1u << a) - 1u) << b,s a的数量在哪里1,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
}
Run Code Online (Sandbox Code Playgroud)
这种方法会破坏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);
}
Run Code Online (Sandbox Code Playgroud)