我希望能够组装/分解字节数据,如以下伪代码所示
//Step one, how do I WriteInt, WriteDouble, WritString, etc to a list of bytes?
List<byte> mybytes = new List<byte>();
BufferOfSomeSort bytes = DoSomethingMagical(mybytes);
bytes.WriteInt(100);
bytes.WriteInt(120);
bytes.WriteString("Hello");
bytes.WriteDouble("3.1459");
bytes.WriteInt(400);
byte[] newbytes = TotallyConvertListOfBytesToBytes(mybytes);
//Step two, how do I READ in the same manner?
BufferOfAnotherSort newbytes = DoSomethingMagicalInReverse(newbytes);
int a = newbytes.ReadInt();//Should be 100
int b = newbytes.ReadInt();//Should be 120
string c = newbytes.ReadString();//Should be Hello
double d = newbytes.ReadDouble();//Should be pi (3.1459 or so)
int e = newbytes.ReadInt();//Should be 400
我会在这里使用BinaryReader
/BinaryWriter
。
// MemoryStream can also take a byte array as parameter for the constructor
MemoryStream ms = new MemoryStream();
BinaryWriter writer = new BinaryWriter(ms);
writer.Write(45);
writer.Write(false);
ms.Seek(0, SeekOrigin.Begin);
BinaryReader reader = new BinaryReader(ms);
int myInt = reader.ReadInt32();
bool myBool = reader.ReadBoolean();
// You can export the memory stream to a byte array if you want
byte[] byteArray = ms.ToArray();
这让我想起了手动XML(反)序列化。如果你有一个可以序列化的对象,或者它只是你想写的"一堆项目",你可能想使用二进制序列化?这里有一个链接,描述了您可以使用BinaryFormatter类和一个代码片段:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.80).aspx
编辑
[Serializable]
public class DummyClass
{
public int Int1;
public int Int2;
public string String1;
public double Double1;
public int Int3;
}
void BinarySerialization()
{
MemoryStream m1 = new MemoryStream();
BinaryFormatter bf1 = new BinaryFormatter();
bf1.Serialize(m1, new DummyClass() { Int1=100,Int2=120,Int3=400,String1="Hello",Double1=3.1459});
byte[] buf = m1.ToArray();
BinaryFormatter bf2 = new BinaryFormatter();
MemoryStream m2 = new MemoryStream(buf);
DummyClass dummyClass = bf2.Deserialize(m2) as DummyClass;
}