二进制格式化程序生成的数组比预期的要大
本文关键字:数组 格式化 程序生成 二进制 | 更新日期: 2023-09-27 18:29:29
为什么使用BinaryFormatter
将Int32
转换为byte[]
时,我会得到一个不到4字节长的数组?
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();
}
}
输出:
54 bytes
BinaryFormatter在序列化时添加了更多信息,比如对象的版本、区域性和程序集。
要获得一个4字节的数组,您需要使用BitConverter.GetBytes(42)
,要返回,请使用BitConverter.ToInt32(bytes, 0)