Reputation: 2352
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?
Upvotes: 4
Views: 4092
Reputation: 58645
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);
Upvotes: 8
Reputation: 13272
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);
Upvotes: 14