问题
I've been asked to export a list of users from ActiveDirectory, and Convert the GUIDs to a numeric equivalent for display (so I'll .ToString that after). I've done some searching but most of the questions are on converting something TO a GUID, or converting a GUID to Int or something silly, (I understand Ints are too small etc..), which arn't really appropriate.
I have the AD stuff sorted and the data exported, however I'm wondering what data type / format to use to convert the GUIDs to, and if it is even possible. I'm not really bothered what exact numeric type is used, as long as the number is still "unique" (I understand that GUIDs arn't really unique etc..).
Are GUIDs in hex based format, and is there any suitable numeric type I can convert them to for display?
I'm using VB.Net and .Net Framework 4. I've tried using BigInteger, but that seems to go into negative numbers too, which I'll use if I have to, but would rather not if there's something else more suitable.
Edit Here's what I tried:
Using a GUID of: f02c7caf-7e5a-491b-9f23-9476174bdda1
And this code:
Dim Foo As String = (New System.Numerics.BigInteger(adUserDirectoryRecord.Guid.ToByteArray())).ToString
It came out as: -125127638954164478915246035839554388817
Note: I'll be outputting this in .csv format once I'm done, for another team to pick up and import into another system, this is likely why they want it in numeric rather than alphanumeric format.
SOLUTION:
As there will be no need to ever convert the Numeric GUID back, BigInteger was the correct method to use for this. The change was to Resize the ByteArray to force it to Positive values only:
'Gets the User's GUID from the Active Directory record, converts it to a Byte Array and Resizes it to Force Positive Values Only:
Dim bytGUIDBytes As Byte() = adUserDirectoryRecord.Guid.ToByteArray()
Array.Resize(bytGUIDBytes, 17)
'Converts the User's GUID Bytes into a Numeric Equivalent, and Returns the String version of the Numerical value.
Return New System.Numerics.BigInteger(bytGUIDBytes).ToString
回答1:
"Numeric" doesn't make sense in VB w.r.t Guid
. There is no 128-bit numeric types in .net. The only 128-bit type is Decimal; but that doesn't seem to make sense to convert a Guid
to a Decimal
. I would simply use ToByteArray
and display the byte values as hex.
Alternatively, make sure the last byte in the array given to BigInteger is zero to get a postive value. e.g.::
var bytes = Guid.NewGuid().ToByteArray();
Array.Resize(ref bytes, 17);
var bigInt = new BigInteger(bytes);
var value = bigInt.ToString();
回答2:
You could simply convert Guid to numeric representation using ToString("n") :
Guid.NewGuid().ToString("n")
will return something like "5ee575bd995b419499aff6d6967c4a35"
来源:https://stackoverflow.com/questions/11849509/convert-guid-to-numeric-equivalent