C# - 读取双精度值
假设只有一个双精度值以二进制格式写入文件中。如何使用 C# 或 Java 读取该值?
如果我必须从一个巨大的二进制文件中找到一个双精度值,我应该使用什么技术来找到它?
Suppose there is only one single double value written into a file in binary format. How can I read that value using C# or Java?
If I have to find a double value from a huge binary file, what techniques should I use to find that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Double 是 8 个字节。要从二进制文件中读取单个双精度数,您可以使用 BitConverter 类:
如果需要从文件中间读取双精度数,请将 0 替换为字节偏移量。
如果不知道偏移量,则无法判断字节数组中的某个值是双精度型、整数还是字符串。
另一种方法是:
第二种方法更适合大文件,因为它不会将整个文件内容加载到内存中。
Double is 8 bytes. To read single double from binary file you can use
BitConverter
class:If you need to read double from the middle of the file, replace 0 with the byte offset.
If you don't know the offset, you can't possibly tell that certain value in the byte array is double, integer or string.
Another approach is:
The second approach is better for big files, as it does not load whole file content to the memory.
您可以使用
BinaryReader
类。对于第二点,如果您知道偏移量,只需使用 Stream.Seek 方法即可。
You can use the
BinaryReader
class.For the second point, if you know the offset, simply use the
Stream.Seek
method.看来我们需要知道 double 值是如何在文件中编码的,然后才能找到它。
It seems that we would need to know how the double value was encoded in the file before we could go about finding it.
1)
2) 你不能。
1)
2) You can't.
以下是如何读取(和出于测试目的而写入)双精度数:
从大文件中获取它取决于数据在文件中的布局方式。
Here's how to read (and write for testing purposes) a double:
Getting it out of a large file depends on how the data is laid out in the file.