Understanding of Logical Operators (Bitwise, oolean) in C# (C Sharp)C# provides
rich set of operators which can be extensively used in your application.
One of the frequently used operators of C# is the logical operators. This
article will focus on different operators grouped under logical operators
category and analyze few of those operators with relevant examples.
C# provides five different logical operators. They are mentioned below: Bitwise
AND Operator denoted by & The first three operators (&, |, ^) works in two different perspectives: Bitwise:
These operators can operate on integral types. In such case, the binary
equivalent of both the numbers will be considered and bitwise computation
will be done. The resultant of this computation will then be converted
back from binary number to integral type. Be it bitwise or Boolean, they can operate on only two operands at a time. And if the operators operate on integral types, the result is an integral type. If they operate on Boolean values, the result will again be a Boolean value. Rest of this article will work on these three operators &, |, ^ and analyze them in both the perspectives Bitwise and Boolean. Normally any number you represent in your code will be internally converted into binary digits. For example, number 2 is equivalent to 00000010; number 3 is equivalent to 00000011 and so on. If you do not have an idea about binary digits and their conversion from decimal, then please read those concepts before proceeding with this article. Bitwise AND Operator (&): Each of these operators has truth table associated with them based on which computation will happen. Truth table for Bitwise AND operator in both the perspectives are mentioned below: Usage of & operator in evaluating both bitwise as well as Boolean expressions are demonstrated below: class sampleClass
{ Output of this code will be: Result1 = 2 Result2 = False Bitwise OR Operator (|) : In & operator, if any of the operand is 0 / false, the result will be 0 / false. In | operator, if any of the operand is 1 / true, then the result will be 1 / true. Truth table for Bitwise OR operator in both the perspectives is mentioned below: Here is an example to demonstrate usage of | operator on integral types as well as Boolean expressions: class sampleClass
{ Output of this code will be: Result1 = 3 Result2 = True Bitwise Exclusive OR Operator (^): While using ^ operator, when both the operands have the same value, the result will be 0 / false. If the operands are different then the result will be 1/ true. Truth table for this operator in both the perspectives is mentioned below: Here is an example to demonstrate usage of ^ operator on integral types as well as Boolean expressions: class sampleClass
{
|