我需要通过将 int
和 float
/double
数据写入其中来构建字节流。如何在 C# 中轻松完成此任务?我知道获取浮点变量的原始字节的方法,但是 C# 是否已经有一个我可以轻松利用的字节流写入系统?
从字节数组中读取浮点值:
uint floatBytes = .. // read 4 float bytes from byte[] array
float floatVal = *((float*)&floatBytes);
将浮点值写入字节数组:
float floatVal = ... // read a float from the float[] array
uint floatBytes = *((uint*)&floatVal);
最佳答案
does C# already have a byte-stream writing system that I could easily leverage?
.NET 库为此提供了一对流装饰器:BinaryWriter 和 BinaryReader。
var reader = new BinaryReader(someStream);
float f1 = reader.ReadSingle(); // Single == float
double d1 = reader.ReadDouble();
string s1 = reader.ReadString(); // the Writer issues a length-prefix.
关于c# - C# 中的可写字节流风格功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10797954/