c# - C# 中的可写字节流风格功能

标签 c# binary floating-point compression arrays

我需要通过将 intfloat/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/

相关文章:

c# - 当与 orderby 一起使用时,是否存在 ascending 关键字纯粹是为了清楚起见?

c# - 如何显示整个十进制

python - 在python中将二进制缓冲区写入文件

matlab - 将十进制转换为二进制向量

c# - 任何人都可以向我解释这个浮点怪异吗?

c++ - 到无穷远并返回

c# - 如何从抽象类访问继承类的属性

C# 交互位置

c - fread 会忽略 ascii 文本吗?

parsing - Haskell:如何将 IO 输入字符串解析为 Float(或 Int 或其他)?