Java 运算符:|= 按位或并赋值示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10142059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:45:47  来源:igfitidea点击:

Java Operators : |= bitwise OR and assign example

javaoperatorsbit-manipulationvariable-assignment

提问by Rachel

I just going through code someone has written and I saw |=usage, looking up on Java operators, it suggests bitwise or and assign operation, can anyone explain and give me an example of it?

我刚刚浏览了某人编写的代码,我看到了|=用法,查找 Java 运算符,它建议按位或和赋值操作,谁能解释一下并给我一个例子?

Here is the code that read it:

这是读取它的代码:

    for (String search : textSearch.getValue())
         matches |= field.contains(search);

回答by Graham Borland

a |= b;

is the same as

是相同的

a = (a | b);

It calculates the bitwise ORof the two operands, and assignsthe result to the left operand.

它计算两个操作数的按位或并将结果分配给左操作数。

To explain your example code:

解释您的示例代码:

for (String search : textSearch.getValue())
    matches |= field.contains(search);

I presume matchesis a boolean; this means that the bitwise operators behave the same as logical operators.

我想matches是一个boolean; 这意味着按位运算符的行为与逻辑运算符相同。

On each iteration of the loop, it ORs the current value of matcheswith whatever is returned from field.contains(). This has the effect of setting it to trueif it was already true, orif field.contains()returns true.

在循环的每次迭代中,它OR是 的当前值以及matches从 返回的任何内容field.contains()。这具有将其设置为true如果它已经为真,或者如果field.contains()返回真的效果。

So, it calculates if anyof the calls to field.contains(), throughout the entire loop, has returned true.

因此,它计算在整个循环中对 的任何调用field.contains()是否已返回true

回答by Alnitak

a |= bis the same as a = (a | b)

a |= b是相同的 a = (a | b)

Boolean Variables

布尔变量

In a booleancontext, it means:

boolean上下文中,这意味着:

if (b) {
    a = true;
}

that is, if bis true then awill be true, otherwise awill be unmodified.

也就是说,如果b为真,则为a真,否则a为未修改。

Bitwise Operations

按位运算

In a bit wise context it means that every binary bit that's set in bwill become set in a. Bits that are clear in bwill be unmodified in a.

在位明智的上下文中,这意味着设置的每个二进制位b都将设置为a。在 中清除的位b将在 中未修改a

So if bit 0 is set in b, it'll also become set in a, per the example below:

因此,如果位 0 设置在 中b,它也将设置在 中a,根据以下示例:

  • This will setthe bottom bit of an integer:

    a |= 0x01

  • This will clearthe bottom bit:

    a &= ~0x01

  • This will togglethe bottom bit:

    a ^= 0x01;

  • 这将设置整数的底部位:

    a |= 0x01

  • 这将清除底部位:

    a &= ~0x01

  • 这将切换底部位:

    a ^= 0x01;

回答by óscar López

This code:

这段代码:

int i = 5;
i |= 10;

is equivalent to this code:

相当于这个代码:

int i = 5;
i = i | 10;

Similarly, this code:

同样,这段代码:

boolean b = false;
b |= true;

is equivalent to this one:

相当于这个:

boolean b = false;
b = b | true;

In the first example, a bit-wise OR is being performed. In the second example, a boolean OR is performed.

在第一个示例中,正在执行按位 OR。在第二个示例中,执行布尔 OR。

回答by adranale

Could it be possible that the code has a bug and it was meant

是否有可能代码有一个错误,它的意思是

matches = matches || field.contains(search);

matches = matches || field.contains(search);

so that matches should be trueif at least one field contains the searchvariable?

true如果至少有一个字段包含search变量,那么匹配应该是?

回答by ?eurobur?

a |= bis the same as a = a | b

a |= b是相同的 a = a | b

a | bis a bitwise operator if both operands are integral types (int, short, etc...). If both operands are booleans, then its is a boolean or.

a | b如果两个操作数都是整数类型(int、short 等...),则为按位运算符。 如果两个操作数都是布尔值,则它是布尔值或。

When both aand bare booleans, the difference between a | band a || bis that in the first, both sides are alwaysevaluated, in the later bis only evaluated if ais false. It is sort of a "shortcut" operator.

aandb都是布尔值时,a | band之间的区别在于a || b,在第一个中,总是对双方进行评估,而在后者b中,只有在a为 false时才进行评估。它是一种“快捷方式”运算符。

This is useful for situations like this:

这对于这样的情况很有用:

if (a == null || a.equals(b)) { .. do something .. } // works

if (a == null | a.equals(b)) { .. do something .. } // NPE if a is null

On the other hand, ||actually is implemented as another conditional jump in the bytecode/machine-code. In some cases, it may be faster to evaluate boolean conditions using the |operator to avoid the additional jump (and thus branch predition, etc...). Definitely something for low-level micro-benchmarking to figure out which is better (and usually not important in most applications).

另一方面,||实际上是作为字节码/机器码中的另一个条件跳转来实现的。在某些情况下,使用|运算符评估布尔条件以避免额外跳转(以及分支预测等)可能会更快。绝对是低级微基准测试以确定哪个更好(并且在大多数应用程序中通常不重要)的东西。

When you do a |= byou are always evaluating both aand b. It doesn't really make sense to have an a ||= boperators, since the equivalent a = a || bwould translate to:

当您这样做时,a |= b您总是同时评估ab。拥有a ||= b运算符并没有真正意义,因为等效项a = a || b将转换为:

if (a) a = true;
else if (b) a = true
else a = false;

...due to the conditional nature of ||evaluation. In other words, bwould not be evaluated if awas already true.

...由于||评估的条件性质。换句话说,b如果a已经是真的,就不会被评估。

回答by Briguy37

That code snippet is a poor example of when to use that operator. Honestly I can't think of a great example of when to use this operator, but here's my best attempt:

该代码片段是何时使用该运算符的一个糟糕示例。老实说,我想不出什么时候使用这个运算符的好例子,但这是我最好的尝试:

boolean somethingIsTrue = testSomethingTrue();
if(somethingIsTrue){
    //Do something
}
somethingIsTrue |= testSomethingElseTrue();
if(somethingIsTrue){
    //Do something else
}
somethingIsTrue |= testSomethingElseTrue2();
if(somethingIsTrue){
    //Do something else than something or something else
}   

Note:You need 3 ifs because otherwise you could just do somethingIsTrue | testSomethingElseTrue()for the second if.

注意:您需要 3somethingIsTrue | testSomethingElseTrue()个 if,否则您只能为第二个 if做。



In case you were wondering why you shouldn't use the operator in the first example, here's why:

如果您想知道为什么不应该在第一个示例中使用运算符,原因如下:

From a performance standpoint, it is poor because it does a compare and an assign for each loop instead of just a compare. Also, it continues iterating even when future iterations will have no effect (once matchesgets set to trueit will not change, and String.containshas no side effects).

从性能的角度来看,它很差,因为它对每个循环进行比较和分配,而不仅仅是比较。此外,即使将来的迭代没有效果matchestrue它也会继续迭代(一旦设置为它就不会改变,并且String.contains没有副作用)。

It is also poor from a readability standpoint, based solely on the existence of this question ;)

从可读性的角度来看,它也很差,仅基于此问题的存在;)

Thus, in place of that snippet I'd go for:

因此,代替那个片段,我会去:

for (String search : textSearch.getValue()){
    if(field.contains(search)){
        matches = true;
        break;
    }
}

On a side note, it seems to me like the original coder might have been playing a bittoo much code-golfwhen (s)he wrote this :)

在一个侧面说明,在我看来,像原来的编码器可能已经打了有点过分码高尔夫球时,他(她)写了这个:)