Flag Group
From TedTycoon.co.uk
I made this .NET class in September 2008 when I was frequently saving booleans in files. I published it on CodeProject originally, so you can download it from there or here - both should be the most recent version. This class should be fairly robust and I don't tend to add any more features to it, but let me know of any bugs and I will consider updating the class. Below is the article I wrote on CodeProject, you can also view it on CodeProject.
Contents |
Introduction
This is a simple structure which stores up to 32 booleans in a 32-bit integer. It is useful for combining many boolean settings into one, two, or four bytes, ready to be saved in a file. Each flag/bit can be accessed using a method or an indexer.
Background
When I create applications with configuration files, I frequently like to keep boolean settings in just one byte or more. I created this structure to allow me to set which bits were on or off, and return a byte/short/integer to save in my configuration file.
Using the code
Flags or bits can be accessed using the set or get methods, or by using the indexer property.
//Declare flag group FlagGroup myFlags = new FlagGroup(); //Set flag myFlags.SetFlag(12, true); myFlags[12] = true; //Get flag bool f = myFlags.GetFlag(12); f = myFlags[12];
There are three properties which allow you to get or set the first byte, or the first two bytes, or all four bytes.
//Set/get group myFlags.Int32 = 0xFFFFFFFF; myFlags.Int16 = 0xAA; myFlags.Int8 = 0;
The ToString() method will return a string containing a binary representation of the flag group.
Implementing the structure
In the demo archive, you will find a DLL of the FlagGroup class in the namespace Ted. This should be added as a reference to your own projects. However, since there is very little code, you might prefer to add the code file to the project, which you will find in the source archive.
If you have any other questions or comments, then please feel free to contact me.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
| |||||
