2

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);
4

2 回答 2

4

does C# already have a byte-stream writing system that I could easily leverage?

The .NET library has a pair of stream-decorators for this, BinaryWriter and 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.
于 2012-05-29T11:18:26.273 回答
1

Use BinaryReader and BinaryWriter

于 2012-05-29T11:18:37.073 回答