5 FIVE of the most used bitwise operations
(see the comments in the code):
1. Showing the most right bit (see line #10):
using System;
class BitwiseOperations
{
static void Main()
{
int a = 7;
Console.WriteLine(Convert.ToString(a, 2).PadLeft(32, '0'));//Seeing the number in bits
int result = a & 1;//using & operator
Console.WriteLine(Convert.ToString(result, 2).PadLeft(32, '0'));//Seeing the most right bit
Console.WriteLine(result);
}
}
2. Showing a bit with defined position (see lines #11 and #14):
using System;
class BitwiseOperations
{
static void Main()
{
int a = 444;
Console.WriteLine("The NUMBER: " + Convert.ToString(a, 2).PadLeft(32, '0'));
int p = 2;
int aRightp = a >> p;//using shift >> operator
Console.WriteLine(" The MASK: " + Convert.ToString(aRightp, 2).PadLeft(32, '0'));
int result = aRightp & 1;//using & operator + putting 1
Console.WriteLine("The RESULT: " + Convert.ToString(result, 2).PadLeft(32, '0'));
Console.WriteLine(result);
}
}
3. Changing user-defined bit with 1 (see lines #11 and #14):
using System;
class BitwiseOperations
{
static void Main()
{
int a = 2;
Console.WriteLine("The NUMBER: " + Convert.ToString(a, 2).PadLeft(32, '0'));
int p = 2;
int mask = 1 << p;//SHIFT operator << on left + putting 1
Console.WriteLine(" The MASK: " + Convert.ToString(mask, 2).PadLeft(32, '0'));
int result = mask | a;//using | operator on the mask and the number
Console.WriteLine("The RESULT: " + Convert.ToString(result, 2).PadLeft(32, '0'));
Console.WriteLine(result);
}
}
4. Changing user-defined bit with 0 (see lines #11 and #14):
using System;
class BitwiseOperations
{
static void Main()
{
int a = 6;
Console.WriteLine("The NUMBER: " + Convert.ToString(a, 2).PadLeft(32, '0'));
int p = 2;
int mask = ~(1 << p);//(using ~) + (SHIFT on left and putting 1)
Console.WriteLine(" The MASK: " + Convert.ToString(mask, 2).PadLeft(32, '0'));
int result = mask & a;//using & operator on the mask and the number
Console.WriteLine("The RESULT: " + Convert.ToString(result, 2).PadLeft(32, '0'));
Console.WriteLine(result);
}
}
5. Changing user-defined bit with the opposite bit (see lines #11 and #14):
using System;
class BitwiseOperations
{
static void Main()
{
int a = 2;
Console.WriteLine("The NUMBER: " + Convert.ToString(a, 2).PadLeft(32, '0'));
int p = 2;
int mask = 1 << p;
Console.WriteLine(" The MASK: " + Convert.ToString(mask, 2).PadLeft(32, '0'));
int result = mask ^ a;//using ^ operator on the mask and the number
Console.WriteLine("The RESULT: " + Convert.ToString(result, 2).PadLeft(32, '0'));
Console.WriteLine(result);
}
}
3 useful videos to watch about bitwise operators in C#:
https://www.youtube.com/watch?v=heRtRoBuV6E
https://www.youtube.com/watch?v=cAe1j8V2PFk
https://www.youtube.com/watch?v=vqztkB-OOzM