我希望能够组装/分解字节数据,如以下伪代码所示
//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();
关于C#字节数组汇编,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9049726/