c++ - 为什么我使用移位运算符 (C++) 得到随机结果?

标签 c++ bit-shift binary-operators

在我一直在编辑的代码中,以前的程序员使用移位运算符将一个适度大的数字添加到 size_t 整数。当我出于调试目的使用这个特定整数时,我发现更改数字不会产生可预测的结果。

输入:

std::size_t
    foo1 = 100000 << 20,
    foo2 = 200000 << 20,
    foo3 = 300000 << 20,
    foo4 = 400000 << 20;
std::cout << "foos1-4:";
std::cout << foo1;
std::cout << foo2;
std::cout << foo3;
std::cout << foo4;

产量:

foos1-4:
1778384896
18446744072971354112
1040187392
18446744072233156608

我知道这是某种溢出错误,但(据我所知有限的知识)size_t 不应该有那些。据我了解, size_t 是一种无符号整数类型,能够容纳几乎无限数量的整数。

根据我对位移运算符的理解,这段代码应该是将数字乘以 2^20 (1048576)。本网站其他页面的链接: What are bitwise shift (bit-shift) operators and how do they work?

注意 - 我手工计算出 foo1 似乎是一个溢出错误,带有 32 位二进制数字截断,但所有其他对我来说似乎完全是随机的。

来自 http://en.cppreference.com/w/cpp/types/size_t : std::size_t 可以存储任何类型(包括数组)理论上可能的对象的最大大小。据此,我认为问题必须出在整数的声明方式或位移位的操作方式上。

这是怎么回事?

最佳答案

问题不在于 std::size_t,而在于所使用的 int 文字。您可以使用 UL 后缀使它们足够长,如下所示:

#include <iostream>

int main()
{
std::size_t
    foo1 = 100000UL << 20,
    foo2 = 200000UL << 20,
    foo3 = 300000UL << 20,
    foo4 = 400000UL << 20;
std::cout << "foos1-4:" << std::endl;
std::cout << foo1 << std::endl;
std::cout << foo2 << std::endl;
std::cout << foo3 << std::endl;
std::cout << foo4 << std::endl;
}

输出:

foos1-4:
104857600000
209715200000
314572800000
419430400000

Live Demo


另请注意,编译器会就此向您发出警告:

main.cpp:6:19: warning: result of '(100000 << 20)' requires 38 bits to represent, but 'int' only has 32 bits [-Wshift-overflow=]
     foo1 = 100000 << 20,
            ~~~~~~~^~~~~
main.cpp:7:19: warning: result of '(200000 << 20)' requires 39 bits to represent, but 'int' only has 32 bits [-Wshift-overflow=]
     foo2 = 200000 << 20,
            ~~~~~~~^~~~~
main.cpp:8:19: warning: result of '(300000 << 20)' requires 40 bits to represent, but 'int' only has 32 bits [-Wshift-overflow=]
     foo3 = 300000 << 20,
            ~~~~~~~^~~~~
main.cpp:9:19: warning: result of '(400000 << 20)' requires 40 bits to represent, but 'int' only has 32 bits [-Wshift-overflow=]
     foo4 = 400000 << 20;
            ~~~~~~~^~~~~

关于c++ - 为什么我使用移位运算符 (C++) 得到随机结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39521374/

相关文章:

c++ - 在 CMake 中处理多个 FIND_PACKAGE 调用

java - 如何简化这个二进制到java类型的代码?

c - 是否可以对多个连续的数组元素进行按位运算?

C: 二进制左旋转

python-3.x - 在 Python3 中重新创建 JS 按位整数处理

c - 一元减号等于 binop 减号吗?

c++ - 在这种情况下如何使用智能指针

c++ - 单击 qchart 图的轴时捕获鼠标事件

python - 使用 ctypes : undefined symbol 将 C++ 函数导出到 python

python - 为什么 numpy 的按位左移在不同的系统上会给出不同的结果?