【发布时间】:2015-07-31 17:25:44
【问题描述】:
我正在尝试将此代码 (from David Clunie) 转换为 C#,以便在我的程序中从 UUID(或 GUID)创建 OID
public static String createOIDFromUUIDCanonicalHexString(String hexString) throws IllegalArgumentException {
UUID uuid = UUID.fromString(hexString);
long leastSignificantBits = uuid.getLeastSignificantBits();
long mostSignificantBits = uuid.getMostSignificantBits();
BigInteger decimalValue = makeBigIntegerFromUnsignedLong(mostSignificantBits);
decimalValue = decimalValue.shiftLeft(64);
BigInteger bigValueOfLeastSignificantBits = makeBigIntegerFromUnsignedLong(leastSignificantBits);
decimalValue = decimalValue.or(bigValueOfLeastSignificantBits); // not add() ... do not want to introduce question of signedness of long
return OID_PREFIX+"."+decimalValue.toString();
我不明白为什么要从 UUID 的各个部分生成 long(leastSignificantBits、mostSignificantBits),然后从它们生成 bigint - 为什么不直接生成 BigInt? (因为他无论如何都要把最重要的数字左移)。
谁能告诉我为什么要这样写? (免责声明:我没有尝试运行 java 代码,我只是想在 C# 中实现它)
[编辑]
原来有几个问题 - 正如 Kevin Coulombe 指出的那样,一个很大的问题是 Microsoft 存储 GUID 的字节顺序。java 代码似乎以明显的(从左到右)顺序获取字节,但有两个显然是分开的块(也感谢 Kevin),因为在 Java 中没有简单的方法来获取整个字节数组。
这是工作 C# 代码,向前和(部分)向后:
class Program
{
const string OidPrefix = "2.25.";
static void Main(string[] args)
{
Guid guid = new Guid("000000FF-0000-0000-0000-000000000000");
//Guid guid = new Guid("f81d4fae-7dec-11d0-a765-00a0c91e6bf6");
Console.WriteLine("Original guid: " + guid.ToString());
byte[] guidBytes = StringToByteArray(guid.ToString().Replace("-", ""));
BigInteger decimalValue = new BigInteger(guidBytes);
Console.WriteLine("The OID is " + OidPrefix + decimalValue.ToString());
string hexGuid = decimalValue.ToHexString().PadLeft(32, '0');//padded for later use
Console.WriteLine("The hex value of the big int is " + hexGuid);
Guid testGuid = new Guid(hexGuid);
Console.WriteLine("This guid should match the orginal one: " + testGuid);
Console.ReadKey();
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
}
【问题讨论】:
-
Guid.Parse()怎么样 - 这不是你要找的吗? -
不,我正在尝试将 GUID 转换为 OID,如下所述:healthcaresecprivacy.blogspot.com/2011/02/…