Register for your free account! | Forgot your password?

Go Back   elitepvpers > Coders Den > General Coding > Coding Tutorials
You last visited: Today at 01:00

  • Please register to post and access all features, it's quick, easy and FREE!

Advertisement



Enums | Bit Flags

Discussion on Enums | Bit Flags within the Coding Tutorials forum part of the General Coding category.

Reply
 
Old   #1
 
»Barney«'s Avatar
 
elite*gold: 0
Join Date: May 2012
Posts: 868
Received Thanks: 947
Enums | Bit Flags

So first of all, this is my first real tutorial here so just go easy on me, Ok ?

If you have some experience with programming languages in general, you must have heard about Enumerations (enums, for short) (And I'm not talking about dynamic collections, neither arrays. Enumerations are known at compile time, which means that they have constant values)

One advantage of using them is that you can't find yourself later on trying to fix a KeyNotFoundException or an IndexOutOfRangeException, since the compiler will give you an error (cleverly enough, I might say).

Also, you should know that there are various ways to create enumerations:
  • static classes with constant members
  • some languages offer the enum data type
(okay, there might be more ways but you got the point)


So, (finally), what are Flags when talking about enums ? Well, while we regurarly use enums to express a single, constant value, there are cases when we need to have more constants in a single object.

Since this is a C# tutorial, the attribute I'm going to use is the System.FlagsAttribute. This sexy guy can be used on enums, and even though it doesn't do anything special, it tells the programmer "HEY, THIS ENUMERATION'S VALUES CAN BE MIXED UP".

Code:
[Flags]
public enum DaysOfWeek { 
	None = 0,
	Monday = 1,
	Tuesday = 2,
	Wednesday = 4,
	Thursday = 8,
	Friday = 16,
	Saturday = 32,
	Sunday = 64
}
This code snippet doesn't do much, but you might wonder why the hell is there a None member ? Well, it's good practice to have a None member in any Flags-marked enumeration.
Code:
if (this.WorkDays == DaysOfWeek.None) { }
is much better than:
Code:
if (this.WorkDays == 0) { }
So, let's see how we can use these things. I will explain everything in more detail after the code section.

Code:
class MyExampleProgram {
	[Flags]
	public enum DaysOfWeek { 
		None = 0,
		Monday = 1,
		Tuesday = 2,
		Wednesday = 4,
		Thursday = 8,
		Friday = 16,
		Saturday = 32,
		Sunday = 64
	}
	
	static void Main() {
		DaysOfWeek workDays = default (DaysOfWeek); // will be set to DaysOfWeek.None (= 0)
		Console.Write("Please write the day you would like to go to work this week (please be serious): ");
		int input = int.Parse(Console.ReadLine());
		
		workDays = (DaysOfWeek) input; // notice the explicit cast
		Console.Write("You will go to work on {0}. Would you like to go to work on an other day too ? Press ENTER if your answer is no.");
		if (Console.ReadLine() == "")
			return;
			
		Console.Write("Please write the other day you would like to go to work this week (please be serious): ");
		int secondInput = int.Parse(Console.ReadLine());
		
		workDays = workDays | (DaysOfWeek) secondInput; 
		// notice we don't use the + operator,
		// insted we will use the Bitwise OR operator
		
		// the same line of code could have been written this way:
		// workDays |= (DaysOfWeek) secondInput;
	}
}
The OR operator combines the two values. If we had these two 4-bit integers in binary: 0110 (= 5) and 1001 (= 9), 0110 | 1001 = 1111 (= 15)

What if we want to check if an enum object has a specific flag? BAM, the Bitwise AND operator (&):

Code:
if (workDays.HasFlag(DaysOfWeek.Monday))
{
	// you're not very lucky
}
this is equivalent to:
Code:
if (workDays & DaysOfWeek.Monday) {
	// you're not very lucky 
}
Implementation of the HasFlag method:
Code:
public class Enum {
	....
	
	public bool HasFlag(Enum flag) {
		return this & flag != 0;
	}
	
	....
}
What if we get sick, or just want to stay in bed for a day? How do we remove a day of work? (programatically speaking, lol)
Here is where we meet the bitwise Negation (~) operator:

Code:
workDays = workDays & ~DaysOfWeek.Saturday; // ...
or even
Code:
workDays &= ~DaysOfWeek.Saturday; // a bit shorter


So, let's review it:
  • add a flag: the OR operator
  • check for a flag: the AND operator
  • remove a flag: the AND; Negation operator

If you have any other questions just post them here

PS: Yes, the values of the DaysOfWeek enum aren't correct here, since Monday | Tuesday = Wednesday, but I think you got the idea. When designing your enums' flags, make sure this won't happen if it isn't a logical combination.
»Barney« is offline  
Thanks
6 Users
Old 08/15/2013, 17:09   #2

 
snow's Avatar
 
elite*gold: 724
Join Date: Mar 2011
Posts: 10,480
Received Thanks: 3,319
Nice tutorial, thanks for that.

1 thing I noticed:

-Does XORing the enum really work?

DaysOfWeek workDays = default(DaysOfWeek);
workDays ^= DaysOfWeek.Monday;
that should be 0 ^= 1 -> 1, right?

A better approach should be workDays &= ~DaysOfWeek.Monday, that's a logical AND with the negation of Monday -> 0 &= ~1.
At least that's how I solve logical combinations.
Would be bad if you'd have to work for an extra day, lol
snow is offline  
Thanks
2 Users
Old 08/16/2013, 09:38   #3
 
»Barney«'s Avatar
 
elite*gold: 0
Join Date: May 2012
Posts: 868
Received Thanks: 947
Quote:
Originally Posted by snow911 View Post
Nice tutorial, thanks for that.

1 thing I noticed:

-Does XORing the enum really work?

DaysOfWeek workDays = default(DaysOfWeek);
workDays ^= DaysOfWeek.Monday;
that should be 0 ^= 1 -> 1, right?

A better approach should be workDays &= ~DaysOfWeek.Monday, that's a logical AND with the negation of Monday -> 0 &= ~1.
At least that's how I solve logical combinations.
Would be bad if you'd have to work for an extra day, lol
You're right, it should be:

Code:
if (workDays & DaysOfWeek.Monday != DaysOfWeek.None)
      workDays ^= DaysOfWeek.Monday;
»Barney« is offline  
Old 08/16/2013, 19:52   #4
 
Schlüsselbein's Avatar
 
elite*gold: 0
Join Date: Feb 2013
Posts: 1,137
Received Thanks: 869
Or simply: workDays &= ~DaysOfWeek.Monday

xor is used to toggle certain bits.
Schlüsselbein is offline  
Thanks
2 Users
Old 02/23/2015, 09:41   #5
 
elite*gold: 0
Join Date: Feb 2015
Posts: 1
Received Thanks: 0
Enum

More about....Enum



Tomi
tomicrow is offline  
Reply


Similar Threads Similar Threads
Is anybody know this flags name ? [HELP]
10/02/2012 - Shaiya Private Server - 3 Replies
Hi there! I am looking for this flags name. (SYMSG-5419-Bootleggery-Vault Guild Auction ' s Flag) Is somebody know this flags name ? I did not found.. THX. http://imgim.com/5431incik4818940.png http://imgim.com/5431incik4818940.png
[RELEASE] Paar Ymir Enums
06/09/2012 - Metin2 PServer Guides & Strategies - 24 Replies
-- EItemTypes ITEM_NONE = 0 ITEM_WEAPON = 1 ITEM_ARMOR = 2 ITEM_USE = 3 ITEM_AUTOUSE = 4 ITEM_MATERIAL = 5 ITEM_SPECIAL = 6 ITEM_TOOL = 7
[5017] Looking for packet enums...
11/03/2011 - CO2 Private Server - 13 Replies
Hello all, I want to know how to get enums, and I`d like to know if someone knows it, whats the status enum for disguise/transformations? EDIT: Yes I already checked the wiki... Thanks in advanced, Jobdvh!
About The DC FLAGS..
09/01/2009 - Cabal Online - 2 Replies
im making a new topic to avoid flaming on the other threads.... im asking for help here.... this is what i did.. 1.)run cabal through cabal rider (bypassed GG) 2.)open ce to set up my lvl 3.)open olly to see whats happening 4.)got myself dc while trying to equip the braces. 5.)got nothing from here on.. 6.)dont know where to change the flags.. though i have idea on how to unpack the cabal exe 7.)i also learned that we need to change the z,o,and c flags for this.. 8.)i just dont know...



All times are GMT +2. The time now is 01:00.


Powered by vBulletin®
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
SEO by vBSEO ©2011, Crawlability, Inc.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Support | Contact Us | FAQ | Advertising | Privacy Policy | Terms of Service | Abuse
Copyright ©2024 elitepvpers All Rights Reserved.