Suppose that you are creating a game in which your character obtains some awards out of some predefined one, as the game goes by. Or, you’re creating software in which you want your user to select some entries/items (imagine something like a checked list box). In both cases, you could try and use these two approaches
- Create or use a data structure (e.g. Dictionary<K,V>) in which you store a reference to all possible items along with the relevant Boolean value. Easy right? In order to answer the question if user has obtained item X, you just check the value of the relevant key in the dictionary.
- Create or use a data structure (e.g. List<T>) in which you store references to the items the user has obtained/picked. So, you can use the List.Contains method to check for an item’s existence.
Both described methods are efficient, easy to grasp and use. However, there is another method in which you do not need to use nothing more advanced than a simple integer. We’ll be using binary system arithmetic and logic to accomplish this purpose.
Each number can be written in binary format in a sequence of 1s and 0s. For instance, 15 is binary 1111 and 2 is binary 0010. Most importantly, all numbers that are a power of two start with 1 and finish with some 0s. Check the below list
Binary – Base 10
1-1
10-2
100-4
1000-8
10000-16
100000-32
1000000-64
…
So, if you assign e.g. “valueA”to 1, “valueB” to 2, “valueC” to 4 etc., you can easily assign multiple values into an integer. How? You just add the relevant base 10 value to this integer, let’s call it storage. For instance, the integer 13 contains 3 values: a)1, b)4, c)8. In binary form, it is written as 1101. The way to check for a value’s existence is a logical bitwise AND between the storage and the respective value. In C#, we use the & for this purpose. If the result of the operation is equal to the value, then storage contains this value. Simple, right? Check the below C# code for the value 19.
int storage = 19; //10011 int a = 1; //1 int b = 2; //10 int c = 4; //100 int d = 8;//1000 int e = 16;//10000 Console.WriteLine("--------------------------------"); Console.WriteLine("Check for the value 19 - 10011"); Console.WriteLine($"Does {storage} contain \"a\" with the value of 1? " + ((storage & a) == a)); //true Console.WriteLine($"Does {storage} contain \"b\" with the value of 2? " + ((storage & b) == b)); //true Console.WriteLine($"Does {storage} contain \"c\" with the value of 4? " + ((storage & c) == c)); //false Console.WriteLine($"Does {storage} contain \"d\" with the value of 6? " + ((storage & d) == d)); //false Console.WriteLine($"Does {storage} contain \"e\" with the value of 8? " + ((storage & e) == e)); //true