• Post Reply Bookmark Topic Watch Topic
  • New Topic

Could someone explain "|=" and "&=" assignment operations?  RSS feed

 
Franco Finstad
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could someone explain "|=" and "&=" assignment operations?

I'm not exactly sure what these operations do and where one would use them in practice.

Thanks!
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
|= does a bitwise OR of the left and right hand operands
&= does a bitwise AND of the left and right hand operands

The result is assigned to the left hand operand.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that operators of the form "a X= b" are just a short-hand notation of "a = a X b".

So "a |= b" is the same as "a = a | b" and "a &= b" is the same as "a = a & b".
 
Campbell Ritchie
Marshal
Posts: 55759
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All sorts of obscure ways you can use them in practice. About a year back we had discussion about how to implement the sort of LED lamps which have seven components in, to show numbers on screen. One way is to have different binary numbers which correspond to the different displays so "8" would come out as 01111111 (it is the only number where all seven bars are illuminated). To find out whether bar 0 is illuminated, you can "and" the number with 00000001.

A typical AND calculation follows:-
10101010 AND
00000001
________
00000000
This particular sum gives 0 throughout because there are no pairs of bits with 1 in both, whereas the following doesn't give 0:-
10101011 AND
00000001
________
00000001

Or gives 1 if either or both the bits at a particular location are 1. copying and pasting gives:-
10101010 OR
00000001
________
10101011

10101011 OR
00000001
________
10101011

There is also XOR (^) which gives 1 if the two bits at the same location are different.
10101010 XOR
00000001
________
10101011

10101011 XOR
00000001
________
10101010

As you have been told | means OR & means AND (and ^ means XOR). a &= b; is shorthand for a = a & b;

CR
 
M Easter
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would check out Bruce Eckel's Thinking in Java for a good look at operators.

It is a great book and available free online. (easily googled)
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!