Parsing binary data (byte[])

  • Thread starter Thread starter Hans Nieser
  • Start date Start date
H

Hans Nieser

Hi,

I'm pretty new to C#, and recently I have been experimenting with sockets.
However, I can't find a nice way (I've been fiddling with for-loops to no
avail) to parse the data that comes in over the socket. I realise this is
a bit of a general subject and there must be some good articles on it, so
any pointers to a good article dealing with this are welcome.

One problem in particular was a response form a gameserver containing
status info. The response basically consists of ASCII values, where each
value has 1 byte prepended to it indicating the field's length (if the
value would have been 3 bytes, the length would be 4).

To make it slightly more complicated, the response also has a few 0x00
(SOH in ASCII) bytes in it, indicating different parts of the response
(kinda like a seperator, seperating general server info, server rules and
players). Also, the last part of the response has a few ASCII values
(player info) 'grouped' by having an extra byte (0x1d if memory serves me)
prepended.

Any help is greatly appreciated.
 
Can you represent the packet as a struct? Post the actual data format of
the packet and maybe sample data and we could help better.
 
William said:
Can you represent the packet as a struct? Post the actual data format of
the packet and maybe sample data and we could help better.

This is an example packet I captured:

http://www.nieser.net/files/bf1942-status.png

And this is an attempt at writing down the data format:

http://www.nieser.net/files/bf1942-status.txt (but since I have no clue on
how to write this kind of thing out, I wouldn't be surprised if noone
understood)

Also I made an error in my first post by saying SOH is 0x00 while it is
actually 0x01.
 
You can use MemoryStream to ease data access, if you can do with streaming
data access to get blocks of data of known size. Later you can use
System.Text.Encoding members to convert this byte stream to readable values.
I would suggest to use streaming data access and no data caching for better
performance (Its for a computer game) , but actually if slow access is
alright, you can go for structure declarations and methods to create its
instance using a byte array or byte stream or whatever u prefer to use.
 
Hans Nieser said:
One problem in particular was a response form a gameserver containing
status info. The response basically consists of ASCII values, where each
value has 1 byte prepended to it indicating the field's length (if the
value would have been 3 bytes, the length would be 4).

Right - so for each value, look at the first byte to see how long the
whole value is (so you know where the next one starts). Then using
Encoding.ASCII.GetString(byte[], int, int) to decode just the right
portion of your byte array.
 
Back
Top