开发者

C Bit fields in C#

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

typedef struct foo  
{  
    unsigned int bar1 开发者_StackOverflow社区: 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?


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) ) ...


You could use the BitArray class for the framework. Look at the msdn article.


Unfortunately there is no such thing in C#. The closest thing is applying a StructLayout attribute and using FieldOffset attribute on fields. However the field offset is in bytes, not in bits. Here is an example:

[StructLayout(LayoutKind.Explicit)]
struct MyStruct
{
    [FieldOffset(0)]
    public int Foo; // this field's offset is 0 bytes

    [FieldOffset(2)]
    public int Bar; // this field's offset is 2 bytes. It overlaps with Foo.
}

But it is NOT the same as the functionality you want.

If what you need is to decode a bits sequence to a struct you will have to write manual code (using, for example, using classes like MemoryStream or BitConverter).


Are you looking for the FieldOffset attribute? See here: FieldOffsetAttribute Class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜