Binary formatter creating larger arrays than expected

Why, when used BinaryFormatterto convert Int32to, byte[]should I get an array of length not 4 bytes?

static class Program
{
    static void Main(string[] args)
    {
        var bf = new BinaryFormatter();

        using(var ms = new MemoryStream())
        {
            bf.Serialize(ms, 42);

            Console.WriteLine($"{ms.ToArray().Length} bytes");
        }

        Console.ReadLine();
    }
}

Output:

54 bytes
+4
source share
1 answer

BinaryFormatter adds a lot more information when it is serialized as the version, culture and assembly from which the objects came.

To just get a 4 byte array you need to use BitConverter.GetBytes(42)to go back you useBitConverter.ToInt32(bytes, 0)

+2
source

Source: https://habr.com/ru/post/1623458/


All Articles