C#中的结构字节/位设置值和操作 [英] Struct Byte/Bit setting values and manipulations in C#
问题描述
大家好,
我在WPF中工作,并且具有一个结构,其中位字段需要类似于C ++中的实现
//MyFile.xaml.cs
我们如何在C#中完成相同的工作?
例如,
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,
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;
上面的代码片段将在我的C#程序中实现,其中在struct的布局是在C/C ++中定义的,我对C#字节内的位操作一无所知.解决上述问题的任何帮助将非常可观.
我正在使用.Net 3.5 Framework,并使用WPF
在此先感谢...
问候,
Samanth_90
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
推荐答案
我相信枚举类型对于位操作而言要好得多:
I believe enumeration types are much better for bit manipulations:
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;
有关使用枚举类型的一些更高级的技术,请参阅我的文章:
枚举类型不枚举!解决.NET和语言限制 [ ^ ].
您还可以将这些面向比特的技术与字节(或任何其他数字类型)访问结合使用.您还可以使用属性[FieldOffset]
(System.Runtime.InteropServices.FieldOffsetAttribute
)创建与同一地址对齐的不同字段,并创建C ++联合的效果.请参阅:
http://msdn.microsoft.com/en-us/library/system. runtime.interopservices.fieldoffsetattribute.aspx [ ^ ].
祝你好运,
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,
这篇关于C#中的结构字节/位设置值和操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!