“|=”是什么意思? C++ 中的操作是什么意思?
我有以下代码,我不明白它的意思:
var1 |= var2>0 ? 1 : 2;
任何人都可以帮助我!
I have the following code and I can't understand what does it mean:
var1 |= var2>0 ? 1 : 2;
Anyone can help me please!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
运算符 |= 表示按位 OR 运算符赋值
The operator |= means Assignment by bitwise OR operator
它是按位或。
It's bitwise-or.
所有
a op= b
运算符都是a = a op b
的快捷方式。然而,由于 C++ 允许单独重写
op
和op=
,因此您依赖于自定义类型的每个实现者保持一致。All the
a op= b
operators are a shortcut toa = a op b
.However since C++ allows
op
andop=
to be overridden separately you rely on each implementer of custom types to be consistent.它的
按位 OR 赋值
是缩写为:
Its the
Assignment by bitwise OR
is short for:
条件?如果 cond 为 true,则 x : y 返回
x
,否则返回y
。阅读 三元运算符a |= b
是 < 的简写代码>a = a | b 正在分配a | b
到a
a | b
是a
的按位或b
。 (例如 2 | 3 = 3 和 1 | 2 = 3 )cond ? x : y
returnsx
if cond is true andy
otherwise. Read Ternary Operatora |= b
is shorthand fora = a | b
which is assigninga | b
toa
a | b
is bitwise OR ofa
andb
. ( e.g. 2 | 3 = 3 and 1 | 2 = 3 )整数可以用二进制表示,因此每个数字(位、开关)都是 1(开)或 0(关):
按位或通过“合并”两组位来组合两个数字:
如果某个位为 1,则输入数字,则结果将为 1。
与按位 AND 进行比较,它会找到两组位的“重叠”:
如果输入数字中的某个位均为 1,则结果将为 1。
如果数字在变量 a 和 b 中,您可以将按位 OR/AND 结果放入新变量 c:
通常需要将结果放入两个变量之一,即
因此,作为简写,您可以这样做只需一步:
Integers can be represented in binary, so that each digit (bit, switch) is 1 (on) or 0 (off):
Bitwise OR combines two numbers by "merging" the two sets of bits:
If a bit is 1 in EITHER of the input numbers, then it will be 1 in the result.
Compare with bitwise AND, which finds the "overlap" of the two sets of bits:
If a bit is 1 in BOTH of the input numbers, then it will be 1 in the result.
If the numbers are in variables a and b, you can place the the bitwise OR/AND results into a new variable c:
Often the result needs to be placed into one of the two variables, i.e.
So as a shorthand, you can do this in a single step:
正如其他人所说,它是
v1 = v1 | 的缩写。 v2;
您可能遇到的另一种用法是布尔值。
鉴于:
而不是说:
你可能会看到:
As others have said it is short for
v1 = v1 | v2;
Another usage you might come across is with booleans.
Given:
Instead of saying:
you might see:
正如我之前的其他人所提到的,这意味着您最终将通过按位或进行赋值。
按位或可以通过取左侧和右侧的位模式并将它们放在彼此的顶部来说明。
在每一列中:0 + 0 给出 0,1 + 0 给出 1,0 + 1 给出 1,1 + 1 给出 1。
在布尔值的上下文中: false OR false == false、true OR false == true、false OR true == true、true OR true == true。
以下是按位 OR 和结果位模式的示例:
var1(11) |= var2(14) -->变量1(15)
As other people before me have mentioned, it means you'll end up with assignments by bitwise OR.
Bitwise OR can be illustrated by taking the left-hand and right-hand side bit-patterns and put them on top of eachother.
In each column: 0 + 0 gives 0, 1 + 0 gives 1, 0 + 1 gives 1, 1 + 1 gives 1.
In the context of booleans: false OR false == false, true OR false == true, false OR true == true, true OR true == true.
Here's an example of bitwise OR and the resulting bit pattern:
var1(11) |= var2(14) --> var1(15)