Forum C# Best way to parse Byte Arrays?

Best way to parse Byte Arrays?

Postby whitershores » July 20th, 2012, 10:58 pm

Hiya, in Flash it is easy and convenient to parse a Byte array of a complex datastructure like a World state:

Code: Select all
myVar1 = stateDataByteArray.readShort()
myVar2 = stateDataByteArray.readDouble();
myVar3 = stateDataByteArray.readInt();


However in C# it seems a bit more complicated, I've found 2 ways to extract the data:

Code: Select all
myVar1 = BitConverter.ToInt32(stateDataByteArray, position);
myVar2 = BitConverter.ToInt32(stateDataByteArray, position +2);

- this one seems especially tedious, having to keep track of the position, and iterate it with irregular intervals(ie Bytes are position +1 but Integers are +4 shorts +2 etc ), which for complex data structures where there are more than one data type seems especially bothersome?

And this one, which has a more similar feel to Flash:
Code: Select all
using (MemoryStream stream = new MemoryStream(stateDataByteArray))  {
    using (BinaryReader reader = new BinaryReader(stream))  {
        Console.WriteLine("myDouble: " + reader.ReadByte());
        Console.WriteLine("myDouble: " + reader.ReadByte());
}}


any other suggestions or ideas? Whats your preferred way?
whitershores
Paid Member
 
Posts: 88
Joined: June 21st, 2011, 4:19 pm

Re: Best way to parse Byte Arrays?

Postby Henrik » July 22nd, 2012, 12:14 pm

Yes, BinaryReader is the way to go. However, as you've undoubtedly noticed when you tried it, it's not on the whitelist for serverside code. I'll try to get it added as soon as possible.

In the meantime, you can make your own super-simple wrapper that acts like it, like this:

Code: Select all
public class SimpleBinaryReader {
    private byte[] data;
    private int position;

    public SimpleBinaryReader(byte[] data) {
        this.data = data;
    }

    public double ReadDouble() {
        var result = BitConverter.ToDouble(data, position);
        position += 8;
        return result;
    }

    public int ReadInt32() {
        var result = BitConverter.ToInt32(data, position);
        position += 4;
        return result;
    }

    //...and so on, for each datatype you actually need.
}
Henrik
.IO
 
Posts: 1880
Joined: January 4th, 2010, 1:53 pm

Re: Best way to parse Byte Arrays?

Postby whitershores » July 22nd, 2012, 5:55 pm

Thanks for the tip Henrik, do let me know when its Whitelisted!

(Btw when I've compiled the debug server, it didn't complain that I've done anthing illegal??, where as usually the debug server says if I've used something that is not allowed ?)
whitershores
Paid Member
 
Posts: 88
Joined: June 21st, 2011, 4:19 pm


Return to C#



cron