How can I simplify the conversion of byte bytes in the network from BinaryReader?

System.IO.BinaryReader reads values ​​in little-endian format.

I have a C # application connecting to my own server-side network library. The server side sends everything in order of the network byte, as expected, but I think that dealing with this on the client side is inconvenient, especially for unsigned values.

UInt32 length = (UInt32)IPAddress.NetworkToHostOrder(reader.ReadInt32()); 

is the only way I got the correct unsigned value from the stream, but it seems awkward and ugly, and I still have to check if it will just click from high values, so I need to have some fun with BitConverter things.

Is there some way that I am missing the description of the wrapper around everything to avoid these ugly conversions on every read? It seems like there should be an endian-ness option for the reader to make this easier, but I haven't seen anything.

+7
c # networking
source share
2 answers

There is no built-in converter. Here is my wrapper (as you can see, I just implemented the functionality I needed, but the structure is pretty easy to change to your liking):

 /// <summary> /// Utilities for reading big-endian files /// </summary> public class BigEndianReader { public BigEndianReader(BinaryReader baseReader) { mBaseReader = baseReader; } public short ReadInt16() { return BitConverter.ToInt16(ReadBigEndianBytes(2), 0); } public ushort ReadUInt16() { return BitConverter.ToUInt16(ReadBigEndianBytes(2), 0); } public uint ReadUInt32() { return BitConverter.ToUInt32(ReadBigEndianBytes(4), 0); } public byte[] ReadBigEndianBytes(int count) { byte[] bytes = new byte[count]; for (int i = count - 1; i >= 0; i--) bytes[i] = mBaseReader.ReadByte(); return bytes; } public byte[] ReadBytes(int count) { return mBaseReader.ReadBytes(count); } public void Close() { mBaseReader.Close(); } public Stream BaseStream { get { return mBaseReader.BaseStream; } } private BinaryReader mBaseReader; } 

Basically, ReadBigEndianBytes does grunts and this is passed to BitConverter. There will be a certain problem if you read a large number of bytes, as this will lead to a large memory allocation.

+5
source share

I created my own BinaryReader to handle all of this. It is available as part of my Nextem library . It also has a very simple way to define binary structures, which I think will help you here - check out the examples.

Note. It is only in SVN right now, but very stable. If you have questions, write to me at cody_dot_brocious_at_gmail_dot_com.

+1
source share

All Articles