要判断输入是否为小端模式,可以使用BitConverter.IsLittleEndian()函数。
我之前也需要执行同样的操作,采用了Paul Smith上面提供的答案,并在此基础上进行了改进,修正了最后一个字节交换的顺序,并将其简化为一次翻转,确保guid.FlipEndian().FlipEndian() == guid。
C# 代码:
public static class Extensions
{
[CLSCompliant(true)]
public static Guid FlipEndian(this Guid guid)
{
var newBytes = new byte[16];
var oldBytes = guid.ToByteArray();
for (var i = 8; i < 16; i++)
newBytes[i] = oldBytes[i];
newBytes[3] = oldBytes[0];
newBytes[2] = oldBytes[1];
newBytes[1] = oldBytes[2];
newBytes[0] = oldBytes[3];
newBytes[5] = oldBytes[4];
newBytes[4] = oldBytes[5];
newBytes[6] = oldBytes[7];
newBytes[7] = oldBytes[6];
return new Guid(newBytes);
}
}
VB.net代码(从在线服务翻译):
导入 System.Runtime.CompilerServices
Module ModuleExtension
''' <summary>
''' A CLSCompliant method to convert a big-endian Guid to little-endian
''' and vice versa.
''' The Guid Constructor (UInt32, UInt16, UInt16, Byte, Byte, Byte, Byte,
''' Byte, Byte, Byte, Byte) is not CLSCompliant.
''' </summary>
<Extension()>
Public Function FlipEndian(guid As Guid) As Guid
Dim newBytes = New Byte(15) {}
Dim oldBytes = guid.ToByteArray()
For i As Integer = 8 To 15
newBytes(i) = oldBytes(i)
Next
newBytes(3) = oldBytes(0)
newBytes(2) = oldBytes(1)
newBytes(1) = oldBytes(2)
newBytes(0) = oldBytes(3)
newBytes(5) = oldBytes(4)
newBytes(4) = oldBytes(5)
newBytes(6) = oldBytes(7)
newBytes(7) = oldBytes(6)
Return New Guid(newBytes)
End Function
End Module