【发布时间】:2016-11-17 20:00:40
【问题描述】:
我有一个结构可以在各处使用,我将它作为 byteArray 存储在 hd 上并发送到其他平台。
我曾经通过获取结构的字符串版本并在序列化过程中使用 getBytes(utf-8) 和 getString(utf-8) 来做到这一点。有了这个,我想我避免了小端和大端的问题?
但是那是相当多的开销,我现在正在使用这个:
public static explicit operator byte[] (Int3 self)
{
byte[] int3ByteArr = new byte[12];//4*3
int x = self.x;
int3ByteArr[0] = (byte)x;
int3ByteArr[1] = (byte)(x >> 8);
int3ByteArr[2] = (byte)(x >> 0x10);
int3ByteArr[3] = (byte)(x >> 0x18);
int y = self.y;
int3ByteArr[4] = (byte)y;
int3ByteArr[5] = (byte)(y >> 8);
int3ByteArr[6] = (byte)(y >> 0x10);
int3ByteArr[7] = (byte)(y >> 0x18);
int z = self.z;
int3ByteArr[8] = (byte)z;
int3ByteArr[9] = (byte)(z >> 8);
int3ByteArr[10] = (byte)(z >> 0x10);
int3ByteArr[11] = (byte)(z >> 0x18);
return int3ByteArr;
}
public static explicit operator Int3(byte[] self)
{
int x = self[0] + (self[1] << 8) + (self[2] << 0x10) + (self[3] << 0x18);
int y = self[4] + (self[5] << 8) + (self[6] << 0x10) + (self[7] << 0x18);
int z = self[8] + (self[9] << 8) + (self[10] << 0x10) + (self[11] << 0x18);
return new Int3(x, y, z);
}
它对我来说效果很好,但我不太确定小/大端的工作原理。当其他机器收到我作为字节数组发送的 int 时,我是否还需要在这里处理一些安全的事情?
【问题讨论】:
-
使用
IPAddress.HostToNetwork方法。目前,如果您的软件将在 big-endian 系统上运行 - 您最终会通过网络发送 little-endian 字节。
标签: c# serialization endianness