开发者

C# deserializing a binary structure with bitfields - how to do?

开发者 https://www.devze.com 2023-02-09 07:20 出处:网络
I have a C struct that is defined in a way similar to this: struct TestStruct { uint flag1 :2; uint flag2 :2;

I have a C struct that is defined in a way similar to this:

struct TestStruct
{
    uint flag1 :2;
    uint flag2 :2;
    uint flag3 :2;
    uint flag4 :2;

    uint value1;
} TestStruct;

I know that I can deserialize a binary struct by using the 开发者_运维百科StructLayout attribute and Marshal.PtrToStructure(). But is there a way to do this with binary fields as shown in the structure where one value is just 2 bits long?

Thanks in advance.


There is no direct support for such a structure in C#. You have to use an integral type holding all the bits and extract the fields from it afterwards.

See the solution to a very similar problem at Bit fields in C#

0

精彩评论

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