开发者

Converting string to flags enum in C#

开发者 https://www.devze.com 2023-03-19 01:53 出处:网络
A device r开发者_如何学Ceports 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 lik

A device r开发者_如何学Ceports 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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消