Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change from bitarray to enum

Tags:

c#

enums

flags

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?

like image 446
David Wallis Avatar asked Apr 17 '16 09:04

David Wallis


2 Answers

just simply cast it to byte!.
example:

byte eventMessages =(byte)( EventMessageTypes.aaa | EventMessageTypes.bbb | EventMessageTypes.ccc);
like image 175
mehrdad safa Avatar answered Oct 15 '22 06:10

mehrdad safa


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
{
   ...
}
like image 22
weston Avatar answered Oct 15 '22 05:10

weston