在 C# 中将字符串转换为标志枚举

发布于 2024-11-18 21:06:46 字数 315 浏览 6 评论 0原文

设备将其限位开关的状态报告为一系列 1 和 0(表示包含“010111110000”的字符串)。这些开关的理想表示是像这样的标志枚举:

[Flags]
public enum SwitchStatus
{
    xMin,
    xMax,
    yMin,
    yMax,

    aMax,
    bMax,
    cMax,
    unknown4,

    unknown3,
    unknown2,
    unknown1,
    unknown0
}

是否可以将字符串表示形式转换为枚举?如果是这样,怎么办?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

他是夢罘是命 2024-11-25 21:06:46

您可以使用 Convert.ToInt64(value, 2)Convert.ToInt32(value, 2) 这将为您提供 long 或 int,然后只需使用

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

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);
旧时模样 2024-11-25 21:06:46

首先,您必须将“二进制字符串”转换为 int。

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

您必须声明枚举项及其各自的编号:

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

最后是映射。您可以从这样的数字中获取枚举:

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

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文