jM2.me
jM2.me

Reputation: 3969

C# Reading Byte Array

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

Upvotes: 3

Views: 17183

Answers (4)

xanatos
xanatos

Reputation: 111940

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?

Upvotes: 2

Marlon
Marlon

Reputation: 20312

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
    }
}

Upvotes: 4

KeithS
KeithS

Reputation: 71591

Why not use a Stream, for instance a NetworkStream?

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064114

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.

Upvotes: 1

Related Questions