Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Transform bytes to structure and back

My goal is to transform array of bytes to c# structure and back. Assume I receive the following data from an external source:

byte[] bytes = {
    0x10, 0x00,
    0x01, 0x00, 0x01, 0x00
};

I know that first two bytes mean "ushort" value, next 4 bytes mean "uint". Bytes come in "high-endian" order. For keeping the decoded result I declare the following structure:

struct Envelop
{
    public ushort Value1;
    public uint Value2;
}

Now I’d like to create an instance of "Envelop" and fill it in according to the data. Is there any standard functionality for that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Envelop data = SomeStandardFunctionality<Envelop>(bytes);

Console.WriteLine(data.Value1); // 16
Console.WriteLine(data.Value2); // 257

I also need possibility to transform this structure back to array which should look exactly at the initial one. I believe that both tasks are parts of the same functionality in c#.

>Solution :

The closest, you can get without going into very unsafe territory is, reading the values separately using BinaryPrimitives.

var data = new Envelop
{
    Value1 = BinaryPrimitives.ReadUInt16LittleEndian(bytes),
    Value2 = BinaryPrimitives.ReadUInt32LittleEndian(bytes[2..])
};

Console.WriteLine(data.Value1); // LittleEndian: 16, BigEndian: 4096
Console.WriteLine(data.Value2); // LittleEndian: 65537, BigEndian 16777472

If you want to directly copy the memory, you can do this, but this is quite unsafe, because your results will depend on the endianess of the system.

var data = new Envelop();
var ptr = new IntPtr(&data);
Marshal.Copy(bytes, 0, ptr, bytes.Length);

Console.WriteLine(data.Value1); // 16
Console.WriteLine(data.Value2); // 65537

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Envelop
{
    public ushort Value1;
    public uint Value2;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading