C# Source Code: Basic bitwise operations
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Basic bitwise operations
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Tuesday, October 17, 2006
Hits:
2482
Category:
General/Framework
Article:
Introduction: ------------- Bitwise operators give you the ability to store multiple settings in a single primitive data type (e.g. an integer). This is useful when a single item has potentially more than one setting of the same type. For example, a message box could have an Ok button, a Cancel button, a Retry button or any combination of the above. By assigning a flag to each button, the complete combination of which buttons to show can be represented in a single primitive data type. Unlike all other articles i have seen in on this topic, i am not going to delve into exactly how this works (bit manipulation), but instead concentrate on how to implement the functionality in C#. If you would like to understand how it all works, start here. Defining the Flags: ------------------- To start of with, declare an enum to list all the possible flags. Two things are important when declaring the enum. The first thing you will probably notice is the [Flags] attribute. This is necessary in order to indicate that the enumeration should be treated as a set of flags. The second important thing is assigning a value to each of the items in the enum. The first value should be 1, then just double the value for each consecutive item. The integer type in .NET can store up to 32 flags. public enum Buttons : int { ···Ok = 1, Cancel = 2, Retry = 4, Help = 8 } Tip: An "All" item could be added to the list of items in the enumeration as follows: All = Ok | Cancel | Retry | Help Setting flags ON: ---------------- To set multiple flags, concatenate the desired flags using the bitwise OR symbol "|": Buttons buttons; buttons = Buttons.Ok | Buttons.Cancel; Setting flags OFF: ------------------ buttons &= ~Buttons.Cancel; Testing to see if a certain flag is set: if ((buttons&Buttons.Ok)==Buttons.Ok) ···Console.WriteLine("Ok");
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet