C# Bitwise Operator

In C#, bitwise operators are used to perform operations on the individual bits of integer values. The basic bitwise operators in C# are:

  • & (bitwise AND)
  • | (bitwise OR)
  • ^ (bitwise XOR)
  • ~ (bitwise NOT)
  • << (left shift)
  • >> (right shift)

Here are some examples of how to use bitwise operators in C#:

refer to‮‬:theitroad.com
int x = 5;    // binary: 0000 0101
int y = 9;    // binary: 0000 1001

int result1 = x & y;    // result1 is 1 (0000 0001)
int result2 = x | y;    // result2 is 13 (0000 1101)
int result3 = x ^ y;    // result3 is 12 (0000 1100)
int result4 = ~x;    // result4 is -6 (1111 1010 in two's complement representation)
int result5 = x << 2;    // result5 is 20 (0001 0100)
int result6 = y >> 1;    // result6 is 4 (0000 0100)

The & operator performs a bitwise AND operation on the corresponding bits of its operands. The result is 1 if both bits are 1, otherwise the result is 0.

The | operator performs a bitwise OR operation on the corresponding bits of its operands. The result is 1 if either bit is 1, otherwise the result is 0.

The ^ operator performs a bitwise XOR (exclusive OR) operation on the corresponding bits of its operands. The result is 1 if the corresponding bits are different, otherwise the result is 0.

The ~ operator performs a bitwise NOT operation on its operand. This operator reverses the bits of the operand. If the operand is an int, then the result is the two's complement representation of the negation of the operand.

The << operator performs a left shift operation on its first operand by the number of bits specified in its second operand. The left shift operation shifts the bits of the operand to the left, filling the empty spaces with zeros.

The >> operator performs a right shift operation on its first operand by the number of bits specified in its second operand. The right shift operation shifts the bits of the operand to the right, filling the empty spaces with zeros or ones, depending on the sign of the operand.

Bitwise operators are used in low-level programming, such as device drivers and embedded systems, where the manipulation of individual bits is important. They can also be used in some algorithms, such as hashing and encryption.