C#字节数组汇编

标签 c# byte

我希望能够组装/分解字节数据,如以下伪代码所示

//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/

相关文章:

c# - 在 Action 方法中调用的好方法

c# - 为什么与小阵列相比,大阵列的C#SIMD的性能增益较低?

c - 在C中,检查字符串中的偏移量并计算字节数

ffmpeg - ffprobe 的数据包大小单位是多少(类似于 ffmpeg)?

c# - 动态gridview——如何在rowdatabound中引用

c# - 运算符 '==' 不能应用于类型 'KeyValuePair' 和 'string' 的操作数?

c# - 在 visual studio 中重建 app.config?

C#/CSS : Convert bytes to CSS hex string

java - 如何在 Android 中创建我的自定义类?

java - Java中图像转换为字节数组