Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a single | or & mean? [duplicate]

Tags:

c#

Possible Duplicate:
What is the diffference between the | and || or operators?
What does | (pipe) mean in c#?

I have some code that was written by another developer in the office, who isn't in at the moment. I have some work to do on his code, but I have not coma across this before. I tried searching on here, but it strips my | out of the search line. I also don't know what the name for that symbol is, so couldn't search for it like that.

this.Action.Values[key] = (int)this.Action.Values[key] | 1;

My question is what does the single or do in this instance?

like image 334
Andrew Avatar asked Mar 16 '12 11:03

Andrew


2 Answers

The Bar (or pipe), | is a bit-wise OR operator, and the easiest way of explaining it is that it allows us to combine flags. Consider:

[Flags]
public enum WindowFlags
{
    None = 0, 
    Movable = 1,
    HasCloseBox = 2,
    HasMinimizeBox = 4,
    HasMaximizeBox = 8
}

Using the bitwise-OR operator, we can combine flags, thusly:

WindowFlags flags = WindowFlags .Movable | WindowFlags .HasCloseBox | WindowFlags .HasMinimizeBox;

We can "test" for a given flag, using:

bool isMovable = (flags & WindowFlags .Movable);

Removing flags is a bit more of a strain on the eyeballs:

flags &= ~WindowFlags.HasCloseBox;  // remove HasCloseBox flag
like image 81
Moo-Juice Avatar answered Sep 30 '22 19:09

Moo-Juice


These are bitwise operations.

Example

  011000101
| 100100100
-----------
= 111100101


  011000101
& 100100100
-----------
= 000000100
like image 28
bytecode77 Avatar answered Sep 30 '22 20:09

bytecode77