4

A device reports status of its limit switches as a series of ones a zeros (meaning a string containing "010111110000"). Ideal representation of these switches would be a flags enum like this:

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

Is it possible to convert the string representation to the enum? If so, how?

2 Answers 2

14

You can use Convert.ToInt64(value, 2) or Convert.ToInt32(value, 2) this will give you either the long or the int, then simply 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); 
Sign up to request clarification or add additional context in comments.

Comments

8

First you have to convert your "binary string" to int.

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

You have to have declared your enum items with their respective numbers:

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

At last, the mapping. You get your enum from the number like this:

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

7 Comments

The flag values will be whatever values come from the binary string
But the string of 1s and 0s is all the switches. 12 digits, 12 enum names. Each enum value should be the value of a single bit. 0x001 through 0x800.
The SwitchStatus flags will not work properly numbered consecutively as you have them - you may as well remove the '[Flags] attribute. I still give +1 because of the usefulness of the answer.
Also, you can't use base as a variable name. It's reserved.
Sigh... I guess people want fully compilable code these days... It's a Q&A site, it's not my production environment. People should find their way through eventual pseudocode fixes. Anyway, fixed it. Getting downvoted for that is just mean...
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.