Bar*_*run 2 .net c# bitconverter c#-4.0
假设只有一个双精度值以二进制格式写入文件中.如何使用C#或Java读取该值?
如果我必须从一个巨大的二进制文件中找到一个double值,我应该使用哪些技术来找到它?
Ale*_*Aza 10
Double是8个字节.要从二进制文件中读取单个double,您可以使用BitConverterclass:
var fileContent = File.ReadAllBytes("C:\\1.bin");
double value = BitConverter.ToDouble(fileContent, 0);
Run Code Online (Sandbox Code Playgroud)
如果需要从文件中间读取double,请将0替换为字节偏移量.
如果您不知道偏移量,则无法判断字节数组中的某个值是double,integer还是string.
另一种方法是:
using (var fileStream = File.OpenRead("C:\\1.bin"))
using (var binaryReader = new BinaryReader(fileStream))
{
// fileStream.Seek(0, SeekOrigin.Begin); // uncomment this line and set offset if the double is in the middle of the file
var value = binaryReader.ReadDouble();
}
Run Code Online (Sandbox Code Playgroud)
对于大文件,第二种方法更好,因为它不会将整个文件内容加载到内存中.