C# Bitwise Operations

Bitwise Operations are those operations applied to data at bit level. Each character (not unicode) takes 1 byte of memory – that’s 8 bits and it’s represented as an array of 0 and 1. A bitwise operation focuses on modifying directly the character’s bits in order to get a new value.
Operators that can be applied to bits:
1 << moves the bits to the left
1 >> moves the bits to the right
2 & applies AND gate between 2 bits
3 | applies OR gate between 2 bits
4 ^ applies XOR gate between 2 bits
5 ~ applies NOT gate


1. Bit Shifting

( symbols: << and >> )
This operators are used to move (shift) the bits to the left (<<) or to the right (>>). It will only move the bits of 1.
Syntax
character << number of moves
number of moves >> character
Example:
Integer 1 is in binary: 00000001. Shifting the bits to the left, means we’ll move all the bits of 1 to the left, so we’ll get 00000010 which is 2 in decimal. If we shift the bits to the right we’ll get 00000000 – which is 0.
binary 0= 0 0 0 0 0 0 0 0
binary 1= 0 0 0 0 0 0 0 1
binary 2= 0 0 0 0 0 0 1 0
Note: you won’t obtain new values if you have no bits of 1 to shift.
Note #2: shifting bits of 1 to the left will return the powers of 2.
Usage in C#

2. AND

( symbol: & )
Aplies the operator AND between 2 bits, from 2 characters.
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
1 & 1 = 1

Syntax
character & character
* not to be confused with the double-and symbol: && which is used in conditional structures
Example: 1 & 3 equals 1. See the table below why:
binary 1= 0 0 0 0 0 0 0 1
binary 3= 0 0 0 0 0 0 1 1
result= 0 0 0 0 0 0 0 1
Usage in C#

3. OR

( symbol: | )
Applies OR, between 2 bits.
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
1 | 1 = 1

Syntax
character | character
* not to be confused with the double-line symbol: || which is used in conditional structures
Example: 1 | 3 equals 3. The table below explains why:
binary 1= 0 0 0 0 0 0 0 1
binary 3= 0 0 0 0 0 0 1 1
result= 0 0 0 0 0 0 1 1
Usage in C#

4. XOR

( symbol: ^ )
Applies XOR between 2 bits, with the following rules:

1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
1 ^ 1 = 0

Syntax
character ^ character
Example: 1 ^ 3 equals 2 :
binary 1= 0 0 0 0 0 0 0 1
binary 3= 0 0 0 0 0 0 1 1
result= 0 0 0 0 0 0 1 0
Usage in C#

5. NOT

( symbol: ~ )
The operator NOT is used to negate a bit:

~1 = 0
~0 = 1

Syntax
~ character
Example: ~2 equals -3
binary 2= 0 0 0 0 0 0 1 0
binary -3= 1 1 1 1 1 1 0 1
Note: You can also negate a number N which is different from 0 by using the following expression: NOT N = -1 * N – 1 => NOT 2 = -3 ; NOT -4 = 3.
Usage in C#
C#
1
2
Console.WriteLine(~2); //outputs -3
 
Previous
Next Post »