MoShe
MoShe

Reputation: 6427

Deserialize byte array

I have a byte array and I need to de-serialize it to several object types.

The object contain {float,short,int}. In Java I would do it with ObjectInputStream like this:

ObjectInputStream is;
is.readFloat()
is.readShort()
is.readInt()

I looking for a way to do it in C#.

Read the first x byte as float the next y byte as short and the next z byte as int.

Upvotes: 0

Views: 2769

Answers (1)

Jim Mischel
Jim Mischel

Reputation: 134005

You want to use a BinaryReader:

If you have a byte array that you want to deserialize, you wrap it in a memory stream and then use the BinaryReader. Like this:

byte[] inputArray;  // somehow you've obtained this
using (var inputStream = new MemoryStream(inputArray))
{
    using (var reader = new BinaryReader(inputStream))
    {
        float f1 = reader.ReadSingle();
        short s1 = reader.ReadInt16();
        int i1 = reader.ReadInt32();
    }
}

You can also do it with the BitConverter class, but you have to maintain state. For example, you can read a float, a short, and an int like this:

byte[] inputArray;
int ix = 0;

float f1 = BitConverter.ToSingle(inputArray, ix);
ix += sizeof(float);  // increment to the next value

short s1 = BitConverter.ToInt16(inputArray, ix);
ix += sizeof(short);

int i1 = BitConverter.ToInt32(inputArray, ix);
ix += sizeof(int);

Of the two, I'd suggest using the BinaryReader, because it's more flexible and easier to work with in most cases. BitConverter is handy if you only have a handful of items to deserialize. I suppose it has the potential of being faster, but that wouldn't matter unless your app is highly performance sensitive. And if deserializing data is that critical, you'd probably write a custom deserializer.

Upvotes: 6

Related Questions