I currently have some crude google code.. that works but I want to swap to an enum.
Currently I need a byte to represent some bit flags that are set,
I currently have this:
BitArray bitArray =new BitArray(new bool[] { true, true, false, false, false, false, false, false });
used in line..
new byte[] {ConvertToByte(bitArray)})
with ConvertToByte from this site...
private static byte ConvertToByte(BitArray bits) // http://stackoverflow.com/questions/560123/convert-from-bitarray-to-byte
{
if (bits.Count != 8)
{
throw new ArgumentException("incorrect number of bits");
}
byte[] bytes = new byte[1];
bits.CopyTo(bytes, 0);
return bytes[0];
}
However I wanted to use an enum as I touched on, so I created it as so:
[Flags]
public enum EventMessageTypes
{
None = 0,
aaa = 1,
bbb = 2,
ccc = 4,
ddd = 8,
eee = 16,
fff = 32,
All = aaa | bbb | ccc | ddd | eee | fff // All Events
}
and then
// Do bitwise OR to combine the values we want
EventMessageTypes eventMessages = EventMessageTypes.aaa | EventMessageTypes.bbb | EventMessageTypes.ccc;
But how do I then get eventMessages to a byte (0x07) I think! so I can append that to my byte array?
just simply cast it to byte!.
example:
byte eventMessages =(byte)( EventMessageTypes.aaa | EventMessageTypes.bbb | EventMessageTypes.ccc);
You have a way of getting a byte
, so now just cast:
byte b = ConvertToByte(bitArray);
EventMessageTypes a = (EventMessageTypes) b;
Also, a tip, restrict the enum range to byte
to prevent someone later adding out of range values to the enum:
[Flags]
public enum EventMessageTypes : byte
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With