Click here to Skip to main content
15,922,015 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi All,

I am working in WPF, and have a struct wherein bit fields needs to be implemented similar to that in C++

//MyFile.xaml.cs

how could we accomplish the same in c#?

for Instance,
C++
typedef struct _PrinterData 
//Similar Struct exists in C++ which needs to be implemented in C#
{
//Bytes #0 -7 // Manupulation of individual bytes.
UINT64 x = 1;
//Bytes #8 ~ 11
UINT32 y = 2;

//Byte #12  ie., Manupilation of bits within bytes
UINT PRINT_EN:1 // #12 [0] Print Enable Bit
UINT PRINT_TYPE:# // #12[1-3] Print Type
UINT Reserved1:4;// #12 [4-7]

} 
PRINTDATA_STRUCT;

The above snippet is to be implemented in my C# program, where in the layout of struct is being defined in C/C++ I had no clue on bit manipulation within byte in C# how could one circumvent the same in C#. Any help in resolving the above would be much appreciable.
I am using .Net 3.5 Framework, using WPF
Thanks in Advance...

With Regards,
Samanth_90
Posted
Updated 18-Mar-12 19:09pm
v2

1 solution

I believe enumeration types are much better for bit manipulations:

C#
enum SomeOptions {
   None = 0,
   FirstOption = 1 << 0,
   SecondOption = 1 << 1,
   ThirdOption = 1 << 2,
   //...
}

// usage:

SomeOptions options; 

//Include a bit:
options |= Options.FirstOption;

//Exclude a bit:
options ^= Options.ThirdOption;

//Arbitrary bit set constructed:
options = Options.SecondOption | Options.FirstOption;

//Check up a bit in a bit set:
bool isFirstOptionSet = (options & Options.FirstOption) > 0;


For some more advanced techniques using enumeration types, please see my article:
Enumeration Types do not Enumerate! Working around .NET and Language Limitations[^].

You can also combine these bit-oriented techniques with byte (or any other numeric type) access. You can also use the attribute [FieldOffset] (System.Runtime.InteropServices.FieldOffsetAttribute) to create different fields aligned to the same address and create effects of C++ union. Please see:
http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.fieldoffsetattribute.aspx[^].

Good luck,
—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900