我试图将一个 int 变量拆分为任意长度的两个部分(即:将 32 位拆分为 31 位和 1 位、30 位和 2 位、16 位和 16 位、1 位和 31 位等)。
我曾尝试使用位移运算符来实现它,但似乎无法使其正常工作。
int botLength = 4;
int start = ~0;
int top = start << botLength;
int bottom = start - top;
std::cout << "Top: " << std::bitset<32>(top) << std::endl;
std::cout << "Bottom: " << std::bitset<32>(bottom) << std::endl;
这输出
Top: 11111111111111111111111111110000
Bottom: 00000000000000000000000000001111
我想要的地方:
Top: 00001111111111111111111111111111
Bottom: 00000000000000000000000000001111
我认为我可以通过将代码更改为以下内容来解决此问题:
int botLength = 4;
int start = ~0;
int top = start << botLength;
int bottom = start - top;
top = top >> botLength; //added this
std::cout << "Top: " << std::bitset<32>(top) << std::endl;
std::cout << "Bottom: " << std::bitset<32>(bottom) << std::endl;
然而,这似乎添加了 1s 作为填充,因为它输出如下:
Top: 11111111111111111111111111111111
Bottom: 00000000000000000000000000001111
谁能建议解决这个问题的方法?
最佳答案
您应该使用无符号值,例如 uint32_t
解决你的问题。使变量 top
无符号。
变量 top
已在您的代码中签名
int botLength = 4;
int start = ~0;
int top = start << botLength;
上面的代码在top
中放了一个负值,那么最左边的符号位(最高位)就是1
。
int bottom = start - top;
top = top >> botLength;
每次右移以保持符号后,符号位将再次设置为1
。所以,所有位 1
。
总的来说,编译器会在每次移位操作后尝试保留有符号整数值的符号。因此,这种机制会影响您的算法,您将无法获得正确的结果。
关于C++ - 将 int 拆分为两个较小的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19775100/