Search code examples
c#arraysbytebinarywriter

How to use BinaryWriter to write double value?


I have two applications that needs to pass value to each other in a fast way, and some value needs to be kept(when I restart my computer it still exist), so I need to create a file, now I know how to do with int:

    using (BinaryWriter writer = new BinaryWriter(new FileStream(@"C:\TEST", FileMode.Open)))
    {
        writer.Write(0);  //00 00 00 00
        writer.Write(1);  //01 00 00 00
        writer.Write(2);  //02 00 00 00
        writer.Write(3);  //03 00 00 00 
        writer.Write(int.MaxValue); //FF FF FF 7F
    }

    byte[] test = new byte[4];
    using (BinaryReader reader = new BinaryReader(new FileStream(@"C:\TEST", FileMode.Open)))
    {

        reader.BaseStream.Seek(8, SeekOrigin.Begin);
        reader.Read(test, 0, 4);
        Console.WriteLine(BitConverter.ToInt32(test, 0));     //2

        reader.BaseStream.Seek(16, SeekOrigin.Begin);
        reader.Read(test, 0, 4);
        Console.WriteLine(BitConverter.ToInt32(test, 0));     //2147483647    

        Console.Read();
    }

But how to do with double?


Solution

  • Its as easy as

    writer.Write((double)int.MaxValue);
    

    BinaryWriter Class

    Write(Double) Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes

    As for reading

    reader.ReadDouble()
    

    BinaryReader.ReadDouble Method ()