我有一个外部数据库正在向我提供信息。一个将其数据保存为本机GUID格式,而我的其他数据源提供标准.NET GUID格式字符串。
是否有一种将原始GUID转换为GUID Structure的整洁方式?
还有任何验证位来确定提供的值是否为Native GUID?如果有的话,我似乎找不到任何东西。
区别如下:
typedef struct _GUID
{
DWORD Data1;
WORD Data2;
WORD Data3;
BYTE Data4[8];
} GUID;
Data1,Data2和Data3的字节顺序相反,但Data4保持不变,有关详细信息,请参阅http://en.wikipedia.org/wiki/Globally_unique_identifier
答案 0 :(得分:10)
要查看输入是否处于小端,或BitConverter.IsLittleEndinan()有帮助。
我只需要做同样的事情,并使用保罗史密斯的答案,我得到它使用此代码。从他的代码中导出,但修复了最后一个字节交换顺序并压缩到一个翻转,确保guid.FlipEndian()。FlipEndian()== guid。
C#代码:
public static class Extensions
{
/// <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>
[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代码(从在线服务翻译):
Imports 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
答案 1 :(得分:1)
如果我正确理解了这个问题,我发布了在How to read a .NET Guid into a Java UUID中执行此操作的扩展方法。
答案 2 :(得分:0)
如果实际上你正在处理Endian问题,你将别无选择,只能自己将字符串解析为Guid
切换Endianness的组成部分,然后create a Guid
即可然后使用。