C Bit fields in C#

David picture David · Feb 25, 2011 · Viewed 7.5k times · Source

I need to translate a C struct to C# which uses bit fields.

typedef struct foo  
{  
    unsigned int bar1 : 1;
    unsigned int bar2 : 2;
    unsigned int bar3 : 3;
    unsigned int bar4 : 4;
    unsigned int bar5 : 5;
    unsigned int bar6 : 6;
    unsigned int bar7 : 7;
    ...
    unsigned int bar32 : 32;
} foo;

Anyone knows how to do this please?

Answer

user1345223 picture user1345223 · May 15, 2013

As explained in this answer and this MSDN article, you may be looking for the following instead of a BitField

[Flags]
enum Foo
{
    bar0 = 0,
    bar1 = 1,
    bar2 = 2,
    bar3 = 4,
    bar4 = 8,
    ...
}

as that can be a bit annoying to calculate out to 232, you can also do this:

[Flags]
enum Foo
{
    bar0 = 0,
    bar1 = 1 << 0,
    bar2 = 1 << 1,
    bar3 = 1 << 2,
    bar4 = 1 << 3,
    ...
}

And you can access your flags as you would expect in C:

Foo myFoo |= Foo.bar4;

and C# in .NET 4 throws you a bone with the HasFlag() method.

if( myFoo.HasFlag(Foo.bar4) ) ...