不同类型变量序列化后的字节形式及转换实现问询
Hey there! Let's break down what's going on with your BinaryFormatter serialization, and why even a simple byte value spits out that long byte sequence.
First off, BinaryFormatter doesn't just serialize the raw value of your variable—it packs full type metadata alongside it. This metadata lets the deserializer exactly recreate the original object (including knowing what type it was) later on. That's why your 1-byte byte variable turns into a much longer byte array: most of those bytes are describing the type, not just the value.
byte Value The sequence you shared (0 1 0 0 0 255 255 255 255 1 0 0 0 0 0 0 0 4 1 0 ...) has three key parts:
- Header bytes: The first few bytes are a marker that identifies this as a .NET serialization stream.
- Type metadata: This chunk includes information about the
System.Bytetype—like its assembly name, type name, and other metadata needed to reconstruct the type during deserialization. - Raw value: Buried in that sequence is the actual
0value you serialized (you’ll spot a single0byte later in the array, that’s your variable’s raw data).
Here’s what you can expect for other common types when using BinaryFormatter:
- Primitive value types (int, float, bool): Each will include type metadata followed by the raw byte representation of the value. For example,
int a = 10will serialize to metadata forSystem.Int32plus 4 bytes (0x0A 0x00 0x00 0x00, since .NET uses little-endian). - Strings: Alongside
System.Stringmetadata, you’ll get the string’s length, encoding info, then the actual byte content of the string. Forstring s = "Hi", that means metadata + length (2) + the bytes0x48 0x69. - Custom structs: The formatter will serialize the struct’s type metadata, followed by metadata and values for each field in the struct. For a struct with an
intandbyte, you’ll see the struct’s metadata first, then the int’s metadata+value, then the byte’s metadata+value. - Null values: The sequence will include a marker indicating null, with no raw value bytes attached.
If your goal is to serialize just the raw value (no extra metadata), BinaryFormatter is overkill. Instead, use lighter-weight options:
- For primitive types, use
BitConverter:BitConverter.GetBytes((byte)0)returns a single0byte, andBitConverter.GetBytes(123)returns the 4-byte int representation. - For custom structs (marked with
[StructLayout(LayoutKind.Sequential)]), use theMarshalclass to copy the struct directly to a byte array. - Use
BinaryWriterto manually write each value to aMemoryStream—this gives you full control over exactly which bytes are output.
内容的提问来源于stack exchange,提问作者John Smith

