Skip to content

Instantly share code, notes, and snippets.

@codejockie
Created January 26, 2024 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codejockie/2568eac29d64c7a5c97707b60905bcf2 to your computer and use it in GitHub Desktop.
Save codejockie/2568eac29d64c7a5c97707b60905bcf2 to your computer and use it in GitHub Desktop.
Use cases of bitwise operators
const byte SECURITY_CHECK_FLAG = 0b00000001;
const byte TWO_FACTOR_AUTH_FLAG = 0b00000010;
const byte JUST_A_FLAG = 0b00000100;
// Uses of Bitwise operators
void Main()
{
// 1. Storing multiple boolean flags
byte flags = 0;
// Enabling flags
flags |= TWO_FACTOR_AUTH_FLAG; // 0b00000010
Console.WriteLine($"{flags:b8} -> {flags}");
flags |= JUST_A_FLAG; // 0b00000110
Console.WriteLine($"{flags:b8} -> {flags}");
// Check flag states
if ((flags & JUST_A_FLAG) == JUST_A_FLAG)
Console.WriteLine($"JUST_A_FLAG_FLAG enabled");
if ((flags & SECURITY_CHECK_FLAG) == 0)
Console.WriteLine("SECURITY_CHECK_FLAG enabled");
// Disabling flags
flags ^= TWO_FACTOR_AUTH_FLAG; // 0b00000100
Console.WriteLine($"{flags:b8} -> {flags}");
// Should not print because flag is disabled
if ((flags & TWO_FACTOR_AUTH_FLAG) == 1)
Console.WriteLine("TWO_FACTOR_AUTH_FLAG enabled");
// 2. Checking for odd or even number
int x = 3;
if ((x & 1) == 0) Console.WriteLine("x is even");
else Console.WriteLine("x is odd");
// 3. Swapping variables without using a third variable
int a = 3, b = 4; // a == 0011; b == 0100
Console.WriteLine("a: {0:b4}, b: {1:b4}", a, b);
a ^= b; // a == 0111; b == 0100
b ^= a; // a == 0111; b == 0011
a ^= b; // a == 0100; b == 0011
Console.WriteLine("a: {0:b4}, b: {1:b4}", a, b);
// 4. Converting text casing
string word = "sREedEv";
var ptr = 0;
while (ptr < word.Length)
{
Console.WriteLine("UPPERCASE: {0}", Convert.ToChar(word[ptr] & '_')); // converts the char into uppercase regardless of the current casing
Console.WriteLine("LOWERCASE: {0}", Convert.ToChar(word[ptr] | ' ')); // converts the char into lowercase regardless of the current casing
ptr++;
}
// 5. Checking if a number is a power of 2
int y = 32;
if (y > 0 && (a & (a - 1)) == 0)
Console.WriteLine("{0} is a power of 2", y);
/*
To understand how the above condition works, we need to understand a property of powers of two. Powers of two when represented in binary have only one set bit i.e., only one bit has the value of 1. Any power of 2, minus 1 would have binary representation where all bits are set except the bit that represents the next number (which is a power of 2).
Using the bitwise AND with the number n and n-1, we can conclude that the number in question is a power of two if it returns 0.
*/
}
// You can define other methods, fields, classes and namespaces here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment