C#字节数组组合(C# Byte array assembly)

编程入门 行业动态 更新时间:2024-10-26 00:27:22
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 400

I 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();

更多推荐

本文发布于:2023-07-17 18:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1148583.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   数组   字节   assembly   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!