mamur mamur - 4 months ago 41
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;

Thank You.


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.

struct X
#if A
    [FieldOffset(0)] public byte a;
    [FieldOffset(1)] public byte b;
    [FieldOffset(0)] public byte b;
    [FieldOffset(1)] public byte a;


    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.