Search code examples
c#binaryreader

Reading UInt16 numbers only binary file


If I were reading byte numbers I would do:

using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    int size = (int) stream.Length;
    BinaryReader br = new BinaryReader(stream);
    byte[] test = new byte[size];
    test = br.ReadBytes(size);
    br.Close();
}

But since I want to read Uint16, I am struck doing:

using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
    int size = (int) stream.Length;
    BinaryReader br = new BinaryReader(stream);
    float[] test = new byte[size/2];
    for (int i = 0; i < size/2; ++i)
    {
         test[i] = br.ReadUInt16();
    }
    br.Close();
}

Is there a faster way to read the whole file at once or is the speed difference negligeable ?


Solution

  • If the file isn't too large to fit in memory, it would be faster to read all the bytes into a MemoryStream and then read Uint16s from that stream. Like so:

    byte[] data;
    int size;
    using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
    {
        size = (int) stream.Length;
        data = new byte[size];
        stream.Read(data, 0, size);
    }
    
    uint[] uintData = new uint[size / 2];
    using (var memoryStream = new MemoryStream(data))
    using (var reader = new BinaryReader(memoryStream))
        for (int i = 0; i < size / 2; i++)
            uintData[i] = reader.ReadUInt16();
    
    // Done.