在我看来,你要小心这样做。想要从 BigEndian 转换为 LittleEndian 的原因是,如果正在读取的字节在 BigEndian 中,并且针对它们计算的操作系统在 LittleEndian 中运行。
C# 不再是一种仅限窗口的语言。使用 Mono 等端口,以及其他 Microsoft 平台,如 Windows Phone 7/8、Xbox 360/Xbox One、Windwos CE、Windows 8 Mobile、Linux With MONO、Apple with MONO 等。操作平台很可能在BigEndian,在这种情况下,如果你在不做任何检查的情况下转换代码,你会搞砸自己。
BitConverter 上已经有一个名为“IsLittleEndian”的字段,您可以使用它来确定操作环境是否为 LittleEndian。然后你可以有条件地进行倒车。
因此,我实际上只是编写了一些 byte[] 扩展而不是创建一个大类:
/// <summary>
/// Get's a byte array from a point in a source byte array and reverses the bytes. Note, if the current platform is not in LittleEndian the input array is assumed to be BigEndian and the bytes are not returned in reverse order
/// </summary>
/// <param name="byteArray">The source array to get reversed bytes for</param>
/// <param name="startIndex">The index in the source array at which to begin the reverse</param>
/// <param name="count">The number of bytes to reverse</param>
/// <returns>A new array containing the reversed bytes, or a sub set of the array not reversed.</returns>
public static byte[] ReverseForBigEndian(this byte[] byteArray, int startIndex, int count)
{
if (BitConverter.IsLittleEndian)
return byteArray.Reverse(startIndex, count);
else
return byteArray.SubArray(startIndex, count);
}
public static byte[] Reverse(this byte[] byteArray, int startIndex, int count)
{
byte[] ret = new byte[count];
for (int i = startIndex + (count - 1); i >= startIndex; --i)
{
byte b = byteArray[i];
ret[(startIndex + (count - 1)) - i] = b;
}
return ret;
}
public static byte[] SubArray(this byte[] byteArray, int startIndex, int count)
{
byte[] ret = new byte[count];
for (int i = 0; i < count; ++i)
ret[0] = byteArray[i + startIndex];
return ret;
}
所以想象一下这个示例代码:
byte[] fontBytes = byte[240000]; //some data loaded in here, E.G. a TTF TrueTypeCollection font file. (which is in BigEndian)
int _ttcVersionMajor = BitConverter.ToUint16(fontBytes.ReverseForBigEndian(4, 2), 0);
//output
_ttcVersionMajor = 1 //TCCHeader is version 1