首页 > 解决方案 > << 运算符如何在以下行中工作

问题描述

我遇到了一行代码。

int m_iCorners = 30 , m_iTesselation2 = 10;
int iNeededSize = (4 + (m_iCorners + 1) * (m_iTesselation2 << 1));

上面代码中操作符的作用是什么,<<它如何影响m_iTesselation2值?

标签: c++

解决方案


<<是左移运算符。它将数字的位向左移动运算符右侧给出的数字。例子:

// Showing only 8 bits here for simplicity (int is 32 bits wide).
int x = 10;    // bits: 0000 1010
int y = x << 1 // bits: 0001 0100 (bits shifted by 1 to the left)
y = x << 2;    // bits: 0010 1000 (bits shifted by 2 to the left)

将 anint向左移动31是未定义的行为。见https://godbolt.org/z/8ShJ9u

y = x << 31; // !!( THIS IS UB, thanks @Ted Lyngmo)
y = x >> 31; // This is fine, y will be 0

请注意,x这里本身并没有改变,而是创建了一个临时值并将值分配给y,就像您已经完成一样y = x + 2

左移通常是将任何内容乘以 2 的快速方法。移动 1 位会产生x * 2. 移位 2 位相当于x * 2 * 2.


推荐阅读