C# Reading Byte Array

14,006

Solution 1

I would say BinaryReader is your best choice. From past experience there are times where you need to inherit from BinaryReader. A primary example is when you need to read a null-terminated string because BinaryReader reads length-prefixed strings. Or you can write your own class, but you will end up providing the same functionality as BinaryReader.

In the end I would probably just create my own class. That way if you need to make changes on how you want to extract the data, you can just edit your class. If you write the entire project with BinaryReader and realize you need to add functionality you will be screwed.

public class MyBinaryReader : BinaryReader
{
    public MyBinaryReader(byte[] input) : base(new MemoryStream(input))
    {
    }

    public override string ReadString()
    {
         // read null-terminated string
    }
}

Solution 2

There is a BitConverter class. Its static members accept a byte array and a starting index and convert the bytes to the specified type. Is it enough?

Solution 3

If it is that simple, then BinaryReader over the stream, or BitConverter directly on the buffer should suffice; and Encoding for strings. But agree endianness first ;)

If it is more complex and object-based, then I suggest using a pre-canned serializer. Writing a full serializer is not trivial.

You might also want to look at a streaming API rather than loading it all into memory - that tends to get expensive for large messages.

Share:
14,006
jM2.me
Author by

jM2.me

Updated on June 28, 2022

Comments

  • jM2.me
    jM2.me almost 2 years

    Okay so I am building server <-> client application.

    Basically server receives a packet that contains header[2bytes], cryptokeys[2bytes],and data

    I was thinking about building class to load whole packet (byte[]) into it and then process the packet with inside class methods. Now to the question. What would be best approach to this? I need to be able to read Int16 Int32 String(int lenght) and probably float

    Edit: Kinda like binaryreader but for byte[] as an input