Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to flags enum in C#

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?

like image 562
Lukas Avatar asked Dec 01 '22 08:12

Lukas


1 Answers

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);
like image 105
Leonard Brünings Avatar answered Dec 02 '22 20:12

Leonard Brünings