01/09
Bitwise operators in C#
Used to perform operations on individual
bits of integer values, such as integers
(int), longs (long), and sometimes other
integral types. These operators allow you
to manipulate and control the individual
bits within a binary representation of a
number.
SWIPE
Kamran Sadin MrSadin@[Link]
02/09
In c#, Bitwise Operators will work on bits, and
these are useful to perform bit by bit operations
such as Bitwise AND (&), Bitwise OR (|), Bitwise
Exclusive OR (^), etc. on operands.
For example, we have integer variables a = 10, b =
20, and the binary format of these variables will be
shown below:
00001010
00010100
-----------
00011110 = 30 (Decimal)
KEEP SWIPING
Kamran Sadin MrSadin@[Link]
03/09
Bitwise AND (&)
It compares each bit of the first operand with the
corresponding bit of its second operand. If both bits are
1, then the result bit will be 1; otherwise, the result will
be 0.
int a = 5, b =10;
int result = a & b;
result => 0;
KEEP SWIPING
Kamran Sadin MrSadin@[Link]
04/09
Bitwise OR (|)
It compares each bit of the first operand with the
corresponding bit of its second operand. If either of the
bit is 1, then the result bit will be 1; otherwise, the result
will be 0.
int a = 5, b =10;
int result = a & b;
result => 15;
KEEP SWIPING
Kamran Sadin MrSadin@[Link]
05/09
Bitwise Exclusive OR, XOR (^)
It compares each bit of the first operand with the
corresponding bit of its second operand. If one bit is 0
and the other bit is 1, then the result bit will be 1;
otherwise, the result will be 0.
int a = 5, b =10;
int result = a ^ b;
result => 15;
KEEP SWIPING
Kamran Sadin MrSadin@[Link]
06/09
Bitwise Left Shift (<<)
It shifts the number to the left based on the specified
number of bits. The zeroes will be added to the least
significant bits.
int a = 5, b =10;
int result = a << 2;
result => 20;
KEEP SWIPING
Kamran Sadin MrSadin@[Link]
07/09
Bitwise Right Shift (>>)
It shifts the number to the right based on the specified
number of bits. The zeroes will be added to the least
significant bits.
int a = 5, b =10;
int result = a >> 2;
result => 1;
KEEP SWIPING
Kamran Sadin MrSadin@[Link]
08/09
Bitwise Complement (~)
It operates on only one operand, and it will invert each
bit of operand. It will change bit 1 to 0 and vice versa.
int a = 5, b =10;
int result = ~a;
result => -6;
KEEP SWIPING
Kamran Sadin MrSadin@[Link]
09/09
Bitwise operators are commonly used in low-level
programming, especially in situations where you need
to manipulate specific bits within integers or perform
operations at the binary level. They can be helpful in
tasks like bit manipulation, flags, and bit-level data
representation.
Share time
Kamran Sadin MrSadin@[Link]