十进制到二进制位图和linq

时间:2016-04-21 10:14:07

标签: c# binary

我有一个应用程序,它使用二进制/十六进制来确定是否启用了设置。这可能是常见的做法,但我是编程的新手,所以我不知道。

Setting 1 = 1
Setting 2 = 2
Setting 3 = 4

数据库中报告的数字将是所有已启用设置的总数,例如7.暗示必须启用所有三个设置,因为总和等于7.

我已经制作了一个元组来报告是否启用了相应的设置。

    public static Tuple<int, string, string, string, string> mytuple(int value)
    {
        switch (value.ToString())
        {
            case "1":
                return new Tuple<int, string, string, string, string>(value, "Disabled", "Disabled", "Disabled", "Enabled");
            case "2":
                return new Tuple<int, string, string, string, string>(value, "Disabled", "Disabled", "Enabled", "Disabled");
            case "3":
                return new Tuple<int, string, string, string, string>(value, "Disabled", "Disabled", "Enabled", "Enabled");
            case "4":
                return new Tuple<int, string, string, string, string>(value, "Disabled", "Enabled", "Disabled", "Disabled");
            case "5":
                return new Tuple<int, string, string, string, string>(value, "Disabled", "Enabled", "Disabled", "Enabled");
            case "6":
                return new Tuple<int, string, string, string, string>(value, "Disabled", "Enabled", "Enabled", "Disabled");
            case "7":
        return new Tuple<int, string, string, string, string>(value, "Disabled", "Enabled", "Enabled", "Enabled");              
            case "8":
        return new Tuple<int, string, string, string, string>(value, "Enabled", "Disabled", "Disabled", "Disabled");
        }

        return new Tuple<int, string, string, string, string>(0, "", "", "", "");
    }

我的问题是,是否有一种更简单的方法可以做到这一点,因为它的二进制和输入值7(二进制111)例如只能以一种方式导出,即所有3个设置都启用,或4(二进制100)实例是一个启用的休息禁用。

可以制作一个方法来确定哪些位是打开/关闭而不是拥有这个巨大的元组(实际的那个运行到2048,所以列表如果很长)。

修改

我已经审核了您的所有建议,并在进行了更多的Google搜索后提出了以下建议。

    static bool[] bitreader(int input)
    {
        int value = input;

        BitArray b = new BitArray(new int[] { value });

        bool[] bits = new bool[b.Count];
        b.CopyTo(bits, 0);

        return bits;
    }

    public void getnotitype(int input, out XElement notitype)
    {
        bool[] f = bitreader(input);

        notitype = (new XElement(("NotificationType"),
                (new XElement("NotifyUsingMessengerService", f[12])),
                (new XElement("SendEmail", f[13])),
                (new XElement("RunCustomCommand", f[14])),
                (new XElement("LogEvent", f[15]))));
    }

    public void getnotiact(int input, out XElement notiact)
    {
        bool[] f = bitreader(input);

        notiact = (new XElement(("MessengerEventLog"),
        (new XElement("LoggingEnabled", f[0])),
        (new XElement("Severe", f[1])),
        (new XElement("Warning", f[2])),
        (new XElement("Informational", f[3])),
        (new XElement("NotifyUser", f[5])),
        (new XElement("SendSNMP", f[6])),
        (new XElement("NotifyAdmin", f[7])),
        (new XElement("SendToAudit", f[11]))));
    }

它的工作正常,它看起来不错吗?

4 个答案:

答案 0 :(得分:2)

您可以使用二进制转换并使用输出。

int value = 7;
int toBase = 2;

//output is a list of characters with 1's and 0's
var output = Convert.ToString(value, toBase).ToList(); 
// gives you list of true/false
var listOfBools = output.Select(x => x=='1'?true:false); 
// gives you list of enabled/disabled string
var listOfStrings = output.Select(x => x=='1'?"enabled":"disabled");

您可以遍历output中的字符以获取启用或禁用的密钥。

答案 1 :(得分:2)

我建议使用以下两个例子之一:

<强> 1。使用包含Enum的标记。

What does the [Flags] Enum Attribute mean in C#?

我可以在这里写更多关于Flags的内容,但整个Flags概念在上面的链接中都有很好的说明。

[Flags]
public enum Setting
{
    Setting1 = 1,
    Setting2 = 2,
    Setting3 = 4,
    Setting4 = 8
}

private Setting GetSetting()
{
    Setting foo =  Setting.Setting1 | Setting.Setting2 | Setting.Setting3;
    return foo;
}

<强> 2。使用ConfigurationSetting

您可以将所有设置包装在一个类中,而不是像您一样使用Tuple。通过使用ConfigurationSection,您还可以将其存储在app / web.config中。

public class MySettings : ConfigurationSection
{
    /// <summary>
    /// Some setting description here...
    /// </summary>
    [ConfigurationProperty("setting1",
        DefaultValue = false,
        IsRequired = true)]
    public bool Setting1
    {
        get { return (bool)this["setting1"]; }
    }
}

public class Foo
{
    public static MySettings GetSettings()
    {
        // Load settings from your configuration.
        return ConfigurationManager.GetSection("mySettings") as MySettings;
    }
}

在你的配置中有这样的东西:

<configSections>
    <section name="mySettings" type="YourNameSpace.MySettings, YourAssembly, Version=1.0.0.0, Culture=neutral"></section>
</configSections>
<mySettings setting1="true" />

答案 2 :(得分:0)

使用[Flags]枚举。

[Flags]
public enum Status
{
    Setting1Enabled = 1,
    Setting2Enabled = 2,
    Setting3Enabled = 4
}

这样你就可以将int解析为支持按位比较的枚举。

要将整数转换为该枚举,请使用Enum.Parse()

Status status = Enum.Parse(typeof(Status), value);

要检查某个值,您只需将其与相应的枚举值进行比较即可。

答案 3 :(得分:0)

我使用Enum进行设置并使用按位运算来设置它们并检查是否设置了标志:

[Flags]
enum MyEnum
{
    Setting1 = 1,
    Setting2 = 2,
    Setting3 = 4,
    Setting4 = 8
}

class Program
{
    static void Main(string[] args)
    {
        var myEnum = MyEnum.Setting1;

        Console.WriteLine(myEnum.HasFlag(MyEnum.Setting1));
        Console.WriteLine(myEnum.HasFlag(MyEnum.Setting2));
        Console.WriteLine(myEnum.HasFlag(MyEnum.Setting3));

        myEnum = MyEnum.Setting2;

        Console.WriteLine(myEnum.HasFlag(MyEnum.Setting1));
        Console.WriteLine(myEnum.HasFlag(MyEnum.Setting2));
        Console.WriteLine(myEnum.HasFlag(MyEnum.Setting3));

        myEnum = MyEnum.Setting2 | MyEnum.Setting3;

        Console.WriteLine(myEnum.HasFlag(MyEnum.Setting1));
        Console.WriteLine(myEnum.HasFlag(MyEnum.Setting2));
        Console.WriteLine(myEnum.HasFlag(MyEnum.Setting3));

        Console.ReadLine();
    }
}