Search code examples
c#stringenum-flags

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?


Solution

  • 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);