Bitwise operators perform calculations on binary numbers. If you don’t know what binary numbers are, they are a series of ones and zeros that represent numerical data. For example, the number 20 is represented as 00010100 in binary. All data in computers are represented by the binary numeral system.
I plan on writing a post in the future about numeral systems but for now, if you want to learn more there are tons of other articles and resources all over the Internet that you can read and use to learn about the binary numeral system.
If you aren’t generally familiar with operators and precedence in programming, then I suggest that you check out my blog post on Working with Operators in C#.
Here are the bitwise operators used in C#:
|&||Bitwise AND operator. Places a bit in the result if it exists in the same place in both operands.|
||||Bitwise OR operator. Places a bit in the result if it exists in either operand.|
|^||Bitwise XOR operator. Places the bit in the result if it's set in one operand but not both.|
|~||Bitwise negation operator. Flips the bit of an operand.|
|<<||Bitwise shift left operator. Shifts the value of the left operand to the left by the value in the right operand.|
|>>||Bitwise shift right operator. Shifts the value of the left operand to the right by the value in the right operand.|
Example using binary operators
byte x = 10; // 00001010 byte y = 5; // 00000101 Console.WriteLine(x & y); // Output: 0 Console.WriteLine(x | y); // Output: 15 (which is 00001111) Console.WriteLine(x ^ y); // Output: 15 (which is 00001111) Console.WriteLine(~x & y); // Output: 5 (which is 00000101) Console.WriteLine(x << y); // Output: 320 (which is 101000000) Console.WriteLine(x >> 1); // Output: 5 (which is 00000101) Console.WriteLine(y >> 2); // Output: 1 (which is 00000001)