When I’m trying to convert an object into byte array I’m getting a wierd array.
this is the code:
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(ms, obj);
Console.WriteLine(ByteArrayToString(ms.ToArray()));
}
//int obj = 50;
//string ByteArrayToString(byte[] byteArr) the functionality of this method is pretty obvious
the result is this:
“00 01 00 00 00 FF FF FF FF 01 00 00 00 00 00 00 00 04 01 00 00 00 0C 53 79 73 74 65 6D 2E 49 6E 74 33 32 01 00 00 00 07 6D 5F 76 61 6C 75 65 00 08 32 00 00 00 0B “
Can somebody explain to me WHY?:) the optimal result should be only “32 00 00 00”.
Since serializer needs to provide enough information to deserialize the data back, it must include some metadata about the object being serialized. Specifically, the
part stands for
System.Int32If you use
BinaryWriterand itsWrite(Int32)method instead, you’ll get the desired effect: your memory stream will contain just the four bytes from your integer. You wouldn’t be able to deserialize it without knowing that you wrote anInt32into the stream.