# C# Bitwise Operators

Either data or code is saved in computer in binary format. The processor of any machine is running by the machine code or binary code. C# Bitwise Operators process the data bit by bit. Comparing with the boolean value true or false, we're using 0 and 1 to stand for each bit in binary. For example, sbyte stands for 8-bit signed integer type. 13 sbyte type is saved in memory as 00001101 in binary. Then -13 is 10001101. The most left bit is sign bit. 0 means positive and 1 means negative. When bitwise operator is used, the result is based on the calculation bit by bit. In bit level, the truth table is shown below.

A | B | ~A | ~B | A&B | A|B | A^B |
---|---|---|---|---|---|---|

1 | 1 | 0 | 0 | 1 | 1 | 0 |

1 | 0 | 0 | 1 | 0 | 1 | 1 |

0 | 1 | 1 | 0 | 0 | 1 | 1 |

0 | 0 | 1 | 1 | 0 | 0 | 0 |

Then bitwise operators can be shown below and assume A=1(00000001) and B=2(00000010) in the examples.

Operator | Name | Usage | Description | Examples |
---|---|---|---|---|

~ | Binary Negation | ~A | Returns the negation for each bit. | sbyte C = ~A; //C is 11111110. |

& | Binary AND | A & B | Returns binary AND for each bit of the operands. | sbyte C = A & B; //C is 00000000. |

| | Binary OR | A | B | Returns binary OR for each bit of the operands. | sbyte C = A | B; //C is 00000011. |

^ | Binary XOR | A ^ B | Returns binary XOR for each bit of the operands. | sbyte C = A ^ B; //C is 00000011. |

<< | Left Shift | A << n | Return n times left shift bit of A. | sbyte C = A << 1; //C 00000010. |

>> | Right Shift | A >> n | Return n times right shift bit of A. | sbyte C = B >> 1; //C 00000001. |

Let's check the result in Example 01-11-01

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

using System; namespace TestLogicalOperators { class Program { static void Main(string[] args) { sbyte a, b; a = 1; b = 2; Console.WriteLine("a={0}, b={1}", a, b); Console.WriteLine("~a={0}, ~b={1}", ~a, ~b); Console.WriteLine("a&b={0}", a&b); Console.WriteLine("a|b={0}", a|b); Console.WriteLine("a^b={0}", a^b); Console.WriteLine("a<<1={0}", a<<1); Console.WriteLine("b>>1={0}", b>>1); Console.Read(); } } }

Output

a=1, b=2 ~a=-2, ~b=-3 a&b=0 a|b=3 a^b=3 a<<1=2 b>>1=1

- Line 9-11: Declare 2 sbyte variables a, b and its initial values.
- Line 12: Output x, y.
- Line 13: Output ~x and ~y. ~x is 11111110 which is -2. For negative number representation, please check here.
- Line 14: Output the result of x&y result 00000000.
- Line 15: Output the result of x|y result 00000011.
- Line 16: Output the result of x^y result 00000011.
- Line 17: Output the result of x<<1 result 00000010.
- Line 18: Output the result of x>>1 result 00000001.