Representing C/C++ unions and bitfields in C#
You are a seasoned C++ applications or embedded programmer, and you need to access an integer bitfield as a set of specific bits. You know how to do this: union myUnion { unsigned int info ; struct { unsigned int flag1 : 1 ; // bit 0 unsigned int flag2 : 1 ; // bit 1 unsigned int flag3 : 1 ; // bit 2 unsigned int flag4 : 1 ; // bit 3 unsigned int flag5 : 1 ; // bit 4 unsigned int flag6 : 1 ; // bit 5 // . // . // . unsigned int flag31 : 1 ; // bit 31 }; }; Supposing, however, you are a C#/.NET programmer. What do you do then? There is no provision or direct support in the language to do this. What tools do you have at your disposal? Well, you do have: [ StructLayout ( LayoutKind . Explicit, Size = 1 , CharSet = CharSet . Ansi)] That will give you the ability to control the byte packing. You also have: [ FieldOffset ( x )] Where: x