0

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.

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

To OP: BinaryReader only takes a Stream object in its constructors, so if all you have is a byte[] array you can simply wrap it in a MemoryStream: = new BinaryReader(new MemoryStream(byteArray))
@Cory: Thanks. I should have mentioned that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.