Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reading Byte Array

Tags:

arrays

c#

packet

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

like image 269
jM2.me Avatar asked Oct 21 '25 13:10

jM2.me


1 Answers

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
    }
}
like image 66
Marlon Avatar answered Oct 23 '25 04:10

Marlon