I have an application that use binary/hex a lot to determine if settings are enabled or not. This is probably common practice but I'm new to programming so I wont know.
Setting 1 = 1
Setting 2 = 2
Setting 3 = 4
The number reported in the database would be a total of all the enabled settings, e.g. 7. The implies that all three settings must be enabled as the sum equals 7.
I've made a tuple to report if the respective setting is enabled/disabled.
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, "", "", "", "");
}
My question is, is there a simpler way to do this since its binary and the input value, 7 (binary 111) for instance can only be derived in one way i.e. all 3 settings enabled, or 4 (binary 100) for instance is one enabled rest disabled.
Can one make a method to determine which bits are on / off instead having this giant tuple (the actual one runs up to 2048 so the list if very long).
EDIT
I've reviewed all your suggestions and came up with the following after more googling.
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]))));
}
Its working fine, does it look OK?