【发布时间】:2013-11-04 19:04:05
【问题描述】:
我正在尝试将一个 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;
然而,这似乎添加了 1 作为填充,因为它输出如下:
Top: 11111111111111111111111111111111
Bottom: 00000000000000000000000000001111
任何人都可以提出解决此问题的方法吗?
【问题讨论】:
-
我认为使用 unsigned int 可以解决问题,但我不完全确定。
-
只是为了好玩,
std::cout << start << std::endl。我想你可能会对结果感到惊讶。 -
打印 -1,但我仍然对为什么使用 unsigned 来修复它感到困惑。无符号不只是告诉编译器如何解释数据吗?实际的二进制文件仍然应该以与 > 相同的方式受到影响(至少我是这么认为的,但它显然没有;))
标签: c++ split bit-manipulation