c++ - 使用 << 的整数运算

标签 c++ operators

我最近看到了很多代码示例,比如

1 << 20 

虽然我知道这个运算符可以用于整数,但我不确定它的作用,我尝试对它进行的每次谷歌搜索都会返回关于 cout << 的内容但没有关于整数运算。谁能告诉我这个运算符对整数做了什么?

最佳答案

<<Bit wise left shift operator

C++03 [ 5.8/2 ]

The value of E1 << E2 is E1 (interpreted as a bit pattern) left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 multiplied by the quantity 2 raised to the power E2, reduced modulo ULONG_MAX+1 if E1 has type unsigned long, UINT_MAX+1 otherwise. [Note: the constants ULONG_MAXand UINT_MAX are defined in the header ). ]

另外在表达式E1 << E2如果E1具有带符号的类型和负值,行为未定义。

这意味着类似于 -1 << 4调用 UB。

关于c++ - 使用 << 的整数运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4074607/

相关文章:

batch-file - 批量不等于(不等)运算符

c# - 在 .NET 中依赖 && 短路安全吗?

c++ - 如何使用预处理器制作跨平台库?

operators - := operator do in Elm? 到底是做什么的

c++ - 使用 enable_if 禁用模板类的模板构造函数

c++ - 如何重置 std::count 返回值

C++ 运算符 < 重载

perl - 在 perl 中 ||= 是什么?

c++ - 蒙特卡洛 C++ 中标准偏差的通用函数

c++ - 表达式必须具有常量值特征矩阵