WinRT API 中似乎不存在 IPAddress 类。是否有等效方法IPAddress.HostToNetworkOrder()
可用于将 int 从主机顺序转换为网络顺序(小端到大端)?
问问题
1456 次
2 回答
3
在许多情况下(当然不是全部),您可以为此使用DataReader和DataWriter:
DataReader reader = new DataReader(stream.AsInputStream());
reader.ByteOrder = ByteOrder.BigEndian; // standard network byte order
reader.ReadInt16();
出于兼容性原因,我使用了反射器:
public static short HostToNetworkOrder(short host)
{
return (short)(((host & 0xff) << 8) | ((host >> 8) & 0xff));
}
public static int HostToNetworkOrder(int host)
{
return (((HostToNetworkOrder((short)host) & 0xffff) << 0x10) | (HostToNetworkOrder((short)(host >> 0x10)) & 0xffff));
}
public static long HostToNetworkOrder(long host)
{
return (long)(((HostToNetworkOrder((int)host) & 0xffffffffL) << 0x20) | (HostToNetworkOrder((int)(host >> 0x20)) & 0xffffffffL));
}
public static short NetworkToHostOrder(short network)
{
return HostToNetworkOrder(network);
}
public static int NetworkToHostOrder(int network)
{
return HostToNetworkOrder(network);
}
public static long NetworkToHostOrder(long network)
{
return HostToNetworkOrder(network);
}
于 2012-08-26T14:55:57.657 回答
1
我最终编写了自己的方法。这真的很简单。它所做的只是颠倒字节顺序。这是为了您的复制和粘贴乐趣:
public static int ReverseEndianness(int num)
{
byte[] bytes = BitConverter.GetBytes(num);
byte[] reversedBytes = new byte[bytes.Length];
for (int i = 0; i < bytes.Length; i++)
{
reversedBytes[i] = bytes[bytes.Length - 1 - i];
}
return BitConverter.ToInt32(reversedBytes, 0);
}
于 2012-08-06T21:46:05.347 回答