Search code examples
c#.netconventions

Object-to-bytes conversion


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".


Solution

  • Since serializer needs to provide enough information to deserialize the data back, it must include some metadata about the object being serialized. Specifically, the

    53 79 73 74 65 6D 2E 49 6E 74 33 32
    

    part stands for System.Int32

    If you use BinaryWriter and its Write(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 an Int32 into the stream.