[C#] C++ Bitfield Struct to C#

Junior Spellweaver
Joined
Sep 16, 2006
Messages
107
Reaction score
8
Hi,

I'm having trouble converting the following C++ struct to C#

Code:
struct CCryptBuffer
{
    unsigned long long AddBufferLen : 11;
    unsigned long long Command : 11;
    unsigned long long AddTableValue : 11;
    unsigned long long EncryptAddValue : 4;
    unsigned long long EncryptValue : 3;
};
Admittedly bit manipulation isn't my strong point but I've had a go and I have the following

Code:
struct CCryptBuffer
{
    private ulong data;

    public ulong Value
    {
        get { return data; }
        set { data = value; }
    }

    public ulong AddBufferLen
    {
        get { return data & 0x7FF; }
        set { unchecked { data = (value & 0x7FF) | (data & (ulong)~0x7FF); } }
    }

    public ulong Command
    {
        get { return (data >> 11) & 0x7FF; }
        set { unchecked { data = ((value & 0x7FF) << 11) | (data & (ulong)~(0x7FF << 11)); } }
    }

    public ulong AddTableValue
    {
        get { return (data >> 22) & 0x7FF; }
        set { unchecked { data = ((value & 0x7FF) << 22) | (data & (ulong)~(0x7FF << 22)); } }
    }

    public ulong EncryptAddValue
    {
        get { return (data >> 33) & 0xF; }
        set { unchecked { data = ((value & 0xF) << 33) | (data & (ulong)~(0xF << 33)); } }
    }

    public ulong EncryptValue
    {
        get { return (data >> 37) & 0x7; }
        set { unchecked { data = ((value & 0x7) << 37) | (data & (ulong)~(0x7 << 37)); } }
    }
};
Now if I use

Code:
CCryptBuffer cryptBuffer;
cryptBuffer.AddBufferLen = 200;
cryptBuffer.Command = 150;
cryptBuffer.AddTableValue = 100;
cryptBuffer.EncryptAddValue = 10;
cryptBuffer.EncryptValue = 5;

printf("0x%X", cryptBuffer);
It will print 0x1904B0C8, if I use the following C# example it will print 0x1904B000 (which means AddBufferLen is 0)

Code:
CCryptBuffer cryptBuffer = new CCryptBuffer()
{
    AddBufferLen = 200,
    Command = 150,
    AddTableValue = 100
    EncryptAddValue = 10,
    EncryptValue = 5
};

Console.WriteLine("0x{0:X}", cryptBuffer.Value & 0x7FFFFFFF);
Any help would be greatly appreciated.

Kind regards,
xadet
 
Last edited:
Back