我最近看到了很多代码示例,比如
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/