在C#中,如果我从二进制文件byte[]
读取“3个32位浮点数”作为Stream
,我将如何提取3个小数?寻找代码来读取数据,然后提取3位小数。假设该文件仅包含“3个32位浮点数”。
答案 0 :(得分:3)
使用BitConvert.ToSingle
:
// numbers to read
var count = 3;
// read file bytes into a buffer
var buffer = new byte[sizeof(float) * count];
var stream = File.OpenRead("path/to/file");
stream.Read(buffer, 0, buffer.Length);
stream.Dispose();
var numbers = Enumerable
.Range(0, count)
// read 32 bits from buffer and convert to float
.Select(index => BitConverter.ToSingle(buffer, index * sizeof(float)))
.ToArray();