0

I have a class:

public class Header
    {
        public int Width { get; set; }
        public int Height { get; set; }
        public byte BitDepth { get; set; }
        public byte ColorType { get; set; }
        public byte CompressionMethod { get; set; }
        public byte FilterMethod { get; set; }
        public byte InterlaceMethod { get; set; }
    }

And array of bytes:

byte[] data = {0, 0, 0, 1, 0, 0, 0, 2, 3, 4, 5, 6, 7};

Bytes directly correspond to values in class eg. Height equals 2 and BitDepth equals 3. Is there any easy way to convert this array to an object or I just have to parse individual values using BitConverter? I've tried to use serialization but it seems that classes contain more information than just field values.

Ava
  • 818
  • 10
  • 18
  • 1
    If you use a struct instead of a class you could do that (but an int will of course be four bytes then). I would not recommend that path though - many pitfalls - been into many of them. :-) – Dan Byström Mar 16 '20 at 19:15

1 Answers1

1

There's no built-in way you could do that.

To be able to parse a byte array as an object, you could try one of the following:

Constructor

One obvious solution is using constructor which takes a byte array as parameter. It requires your byte array to be constructed in a certain way so that you read bytes from the array, convert to values of properties.

public Header (byte[] data)
{
    Width = BitConverter.ToInt32(data, 0);
    Height = BitConverter.ToInt32(data, 4);
    // etc
}

You might need to deal with big endian vs little endian if your code is going to run on or your data is from other OS like Unix.

Indirection Struct

It is possible to read byte array as struct in C#: Reading a C/C++ data structure in C# from a byte array You could then create a class instance from that struct. However, this might require you to have duplicate field / property definitions in both types.

Binary Serialization

If your byte array was a binary representation of an object in C#, you could consider binary serialization. However, binary representation is very slow.

https://learn.microsoft.com/en-us/dotnet/standard/serialization/binary-serialization

Community
  • 1
  • 1
weichch
  • 9,306
  • 1
  • 13
  • 25
  • Thank you. After trying with struct I fell into endianness trap. I will choose the way with constructor, where endianness problem can be solved easily. – Ava Mar 16 '20 at 19:57