Created
April 3, 2025 08:04
-
-
Save deer-roy/a7f23f943cb3c720be3f87d930927383 to your computer and use it in GitHub Desktop.
Bitwise flags in c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
[Flags] | |
public enum PizzaToppings | |
{ | |
Cheese = 1, | |
Bacon = 1 << 1, | |
Avo = 1 << 2, | |
Pineapple = 1 << 3, | |
Mushrooms = 1 << 4, | |
Pepperoni = 1 << 5 | |
} | |
public static class Toppings | |
{ | |
// public const uint Cheese = 1; // 0b000001 | |
// public const uint Bacon = 2; // 0b000010 | |
// public const uint Avo = 4; // 0b000100 | |
// public const uint Pineapple = 8; // 0b001000 | |
// public const uint Mushrooms = 16; // 0b010000 | |
// public const uint Pepperoni = 32; // 0b100000 | |
public const uint Cheese = 1; | |
public const uint Bacon = 1 << 1; | |
public const uint Avo = 1 << 2; | |
public const uint Pineapple = 1 << 3; | |
public const uint Mushrooms = 1 << 4; | |
public const uint Pepperoni = 1 << 5; | |
} | |
public static bool CanTheyOrder( | |
uint userToppings, | |
uint availableToppings | |
) => (availableToppings & userToppings) == userToppings; | |
public static bool CanTheyOrder( | |
PizzaToppings userToppings, | |
PizzaToppings availableToppings | |
) => (availableToppings & userToppings) == userToppings; | |
public static void Main() | |
{ | |
var goodUserChoice = PizzaToppings.Avo| PizzaToppings.Mushrooms; | |
var badUserChoice = PizzaToppings.Pepperoni | PizzaToppings.Mushrooms; | |
var availableChoice = PizzaToppings.Pineapple | PizzaToppings.Mushrooms | |
| PizzaToppings.Cheese | PizzaToppings.Avo; | |
string userBadChoiceBin = Convert.ToString((uint)badUserChoice, 2); | |
string userGoodChoiceBin = Convert.ToString((uint)goodUserChoice, 2); | |
string availableChoiceBin = Convert.ToString((uint) availableChoice, 2); | |
Console.WriteLine($"User Good Choice: {userGoodChoiceBin}"); | |
Console.WriteLine($"User Bad Choice: {userBadChoiceBin}"); | |
Console.WriteLine($"Available Choice: {availableChoiceBin}"); | |
if(CanTheyOrder(goodUserChoice, availableChoice)){ | |
Console.WriteLine("They can order it."); | |
} else { | |
Console.WriteLine("Nope, not available."); | |
} | |
if(CanTheyOrder(badUserChoice, availableChoice)){ | |
Console.WriteLine("They can order it."); | |
} else { | |
Console.WriteLine("Nope, not available."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment