开发者

C# - Read a double value

开发者 https://www.devze.com 2023-03-14 12:07 出处:网络
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?
  1. 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?

  2. If I开发者_StackOverflow have to find a double value from a huge binary file, what techniques should I use to find that?


Double is 8 bytes. To read single double from binary file you can use BitConverter class:

var fileContent = File.ReadAllBytes("C:\\1.bin");
double value = BitConverter.ToDouble(fileContent, 0);

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:

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();
}

The second approach is better for big files, as it does not load whole file content to the memory.


You can use the BinaryReader class.

double value;
using( Stream stream = File.OpenRead(fileName) )
using( BinaryReader reader = new BinaryReader(stream) )
{
    value = reader.ReadDouble();
}

For the second point, if you know the offset, simply use the Stream.Seek method.


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)

        double theDouble;
        using (Stream sr = new FileStream(@"C:\delme.dat", FileMode.Open, FileAccess.Read))
        {
            byte[] buffer = new byte[8];
            sr.Read(buffer, 0, 8);

            theDouble = BitConverter.ToDouble(buffer, 0);
        }

2) You can't.


Here's how to read (and write for testing purposes) a double:

    // Write Double
    FileStream FS = new FileStream(@"C:\Test.bin", FileMode.Create);
    BinaryWriter BW = new BinaryWriter(FS);

    double Data = 123.456;

    BW.Write(Data);
    BW.Close();

    // Read Double
    FS = new FileStream(@"C:\Test.bin", FileMode.Open);
    BinaryReader BR = new BinaryReader(FS);

    Data = BR.ReadDouble();
    BR.Close();

Getting it out of a large file depends on how the data is laid out in the file.


using (FileStream filestream = new FileStream(filename, FileMode.Open))
using (BinaryReader reader = new BinaryReader(filestream))
{
    float x = reader.ReadSingle();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号