考虑到我的数据类型的字节顺序,我遇到了问题。我必须使用 TCP / IP 通过以太网发送数据。然而,字节顺序在发送时需要为大端,在接收时为大端。因此,我尝试在使用此类发送之前反转我的所有日期:
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.
}
这工作正常,直到我像这样分配转换后的值:
ReverseBinaryReader binReader = new ReverseBinaryReader(new MemoryStream(content));
this.Size = binReader.ReadInt16(); // public short Size
例如,如果我想将字节:0x00、0x02 保存为大端,我希望在内存中:0x0200 但是大小的短值将变为 0x0002。这是为什么?
有任何想法吗?谢谢,同行
// 编辑 2:
为了澄清这个问题,我将尝试展示一个示例:
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 } );
}
}