今天碰到一个问题,手上有一个二进制文件,里面的数据是由一个一个的float32类型数值组成,现在需要在C#中读取这个文件中的所有数据。
首先找到C#中用于读取二进制文件的有BinaryReade这个类,那么关于这个类的描述及其方法参见MSDN:
https://msdn.microsoft.com/en-us/library/system.io.binaryreader_methods(v=vs.110).aspx
我们可以看到,这个类中有很多不同的ReadXXX函数,用于读取不同类型的数据,然而并没有float32这种类型的读取方法。
后来我想到的一个解决方法是使用ReadBytes(Int32)这个方法,方法描述如下:
Reads the specified number of bytes from the current stream into a byte array and advances the current position by that number of bytes.
也就是说我们可以自己设定一次读取多少个字节的数据。
那么1个float32类型的数据其实也就是由32位二进制码组成,也就是4个bytes。
所以我们可以通过ReadBytes(4)来实现一次读取4个bytes,这4个bytes也就组成了一个float32值。
那么如何将这4个bytes转换成一个float32值呢?网上找到的方法见链接:
http://stackoverflow.com/questions/2619664/c-convert-byte-array-into-a-float
所以整体而言可以这样来实现整个过程:
BinaryReader br = new BinaryReader(new FileStream("D:\\1.binary", FileMode.Open));
Byte[] byteForFloat;
for(byteForFloat=br.ReadBytes(4); byteForFloat.Length==4;)
{
float myFloat = System.BitConverter.ToSingle(byteForFloat, 0);
byteForFloat= br.ReadBytes(4); }
更新:
今天突然发现BinaryReader里面是有读取Float32的方法的
ReadSingle() |
Reads a 4-byte floating point value from the current stream and advances the current position of the stream by four bytes. |