mamur mamur - 11 days ago 4
C# Question

Using nibbles in struct C#

Can we work with nibbles in C# struct like C++?.
Is there any equivalent code in C#?

typedef struct PHeader {
#if defined(LITTLE_ENDIAN)
uint8_t mHdrLen :4;
uint8_t mVer :4;
#elif defined (BIG_ENDIAN)
uint8_t mVer :4;
uint8_t mHdrLen :4;
#endif
}


Thank You.

Answer

You can achieve same result using [StructLayout(LayoutKind.Explicit)] and FieldOffset attribute. You can read more about it here and here.

But please note that FieldOffset works in byte unit, not bit.

[StructLayout(LayoutKind.Explicit)]
struct X
{
#if A
    [FieldOffset(0)] public byte a;
    [FieldOffset(1)] public byte b;
#else
    [FieldOffset(0)] public byte b;
    [FieldOffset(1)] public byte a;
#endif
}

Example:

unsafe
{
    short x = 12300;
    X* y = (X*)&x;
    X t = *y;

    Console.WriteLine(t.a + " - " + t.b);
}

If you run that code with undefined A, you will get result 48 - 12 but if you #define A, then you will get result 12 - 48.

Comments