c++ - << 运算符如何在以下行中工作
问题描述
我遇到了一行代码。
int m_iCorners = 30 , m_iTesselation2 = 10;
int iNeededSize = (4 + (m_iCorners + 1) * (m_iTesselation2 << 1));
上面代码中操作符的作用是什么,<<
它如何影响m_iTesselation2
值?
解决方案
<<
是左移运算符。它将数字的位向左移动运算符右侧给出的数字。例子:
// 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
.
推荐阅读
- javascript - 我在尝试在 Vue 中重写此 JavaScript 点击事件时遇到问题
- spring-boot - 如何使用spring boot发送邮件?
- r - 使用 R 的 ROC 曲线图(错误代码:预测变量必须是数字或有序)
- javascript - 输入掩码日期时间修改
- mysql - 错误 -4850 无效的模式名称 JPA/EJB,我该如何解决?
- java - Android SearchView 重叠
- rust - Rust:在实现 trait 时如何从周围的范围访问状态而不显式地将其作为参数传递?
- woocommerce - 可变产品默认期权销售价格
- php - 如何使用模态引导程序显示复选框数据
- python - Google Cloud PubSub python 订阅者泄漏内存