C++ - 将 int 拆分为两个较小的数据类型

标签 c++ split bit-manipulation

我试图将一个 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/

相关文章:

c++ - 将 SDL2 与 CMake 一起使用

python - 在 Python 中分解这个字符串的最佳方法是什么?

bit-manipulation - AVX 或其他设置指令可以在给定多个并行整数的索引的情况下提取特定位?

scala - Scala中的位字段

c - 确定 32 位 int 的符号

c++ - 使用 GLSL 直接在着色器中从位置计算平移矩阵

c++ - 使用 Boost Asio 查找服务器 IP

c++ - 在 C++ 中有效地使用继承

linux - 查找并拆分命令但结果到不同的目录?

postgresql - 拆分 PostgreSQL 查询过滤