C#字节数组组合(C# Byte array assembly)
我希望能够组装/解散字节数据,如下面的psuedocode所示
//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 400I would like to be able to assemble/dissasemble byte data, as demonstrated in the following psuedocode
//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();I would use BinaryReader/BinaryWriter here.
// 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();更多推荐
发布评论