I have a problem considering the endianness of my data types. I have to send data over the ethernet using TCP / IP. The byte order however needs to be big endian when being sent and is in big endian, when being received. Therefore I try to reverse all my date before sending it using this class:
class ReverseBinaryReader : BinaryReader
{
private byte[] a16 = new byte[2];
private byte[] ua16 = new byte[2];
private byte[] a32 = new byte[4];
private byte[] a64 = new byte[8];
private byte[] reverse8 = new byte[8];
public ReverseBinaryReader(System.IO.Stream stream) : base(stream) { }
public override int ReadInt32()
{
a32 = base.ReadBytes(4);
Array.Reverse(a32);
return BitConverter.ToInt32(a32, 0);
}
public override Int16 ReadInt16()
{
a16 = base.ReadBytes(2);
Array.Reverse(a16);
return BitConverter.ToInt16(a16, 0);
}
[ . . . ] // All other types are converted accordingly.
}
This works fine till I assign the converted values like this:
ReverseBinaryReader binReader = new ReverseBinaryReader(new MemoryStream(content));
this.Size = binReader.ReadInt16(); // public short Size
For example, if I want to save the bytes: 0x00, 0x02 as big endian, I would expect this in the memory: 0x0200 however the short value of Size would become 0x0002. Why is that?
Any ideas? Thanks, Peer
// Edit 2:
To clear the issue up a little I'll try to show an example:
public class Message {
public short Size;
public byte[] Content;
public Message(byte[] rawData)
{
ReverseBinaryReader binReader = new ReverseBinaryReader(new MemoryStream(rawData));
this.Size = binReader.ReadInt16(); // public short Size
this.Content = binReader.ReadBytes(2); // These are not converted an work just fine.
}
}
public class prog {
public static int main()
{
TCPClient aClient = new TCPClient("127.0.0.1",999); // Async socket
aClient.Send(new Message(new byte[] { 0x00, 0x02 } );
}
}
a16
have and what value is returned byreturn BitConverter.ToInt16(a16, 0);
– Trisped