Convert string to list of flags in C #

The device reports the status of its limit switches, as a number of them are zeros (which means a line containing "010111110000"). An ideal representation of these switches would be an enumeration of such flags:

[Flags] public enum SwitchStatus { xMin, xMax, yMin, yMax, aMax, bMax, cMax, unknown4, unknown3, unknown2, unknown1, unknown0 } 

Is it possible to convert a string representation to an enumeration? If so, how?

+4
source share
2 answers

You can use Convert.ToInt64(value, 2) or Convert.ToInt32(value, 2) , this will give you a long or int, and then just use

 [Flags] public enum SwitchStatus : int // or long { xMin = 1, xMax = 1<<1, yMin = 1<<2, yMax = 1<<3, ... } SwitchStatus status = (SwitchStatus)Convert.ToInt32(value, 2); 
+12
source

First you need to convert the "binary string" to int.

 String binString = "010111110000"; int number = Integer.parseInt(binString, 2); 

You must indicate your listing elements with your numbers:

 [Flags] public enum SwitchStatus { xMin = 1, xMax = 2, yMin = 4, //... unknown0 = 32 //or some other power of 2 } 

Finally, the mapping. You get your list from a number like this:

 SwitchStatus stat = (SwitchStatus)Enum.ToObject(typeof(SwitchStatus), number); 
+6
source

All Articles