开发者

Convert GUID to string in decimal base (aka to a huge, comma delimited integer, in base ten)

开发者 https://www.devze.com 2023-01-25 08:14 出处:网络
How can I convert a System.GUID (in C#) to a string in decimal base (aka to a huge, comma delimited integer, in base ten)?

How can I convert a System.GUID (in C#) to a string in decimal base (aka to a huge, comma delimited integer, in base ten)?

Something like 433,352,133,455,122,445,557,129,...

Guid.ToString converts GUIDs to hexadeci开发者_高级运维mal representations.

I'm using C# and .Net 2.0.


Please be aware that guid.ToByteAray() will NOT return an array that can be passed to BigInteger's constructor. To use the array a re-order is needed and a trailing zero to ensure that Biginteger sees the byteArray as a positive number (see MSDN docs). A simple but less performing function is:

private static string GuidToStringUsingStringAndParse(Guid value)
{
   var guidBytes = string.Format("0{0:N}", value);
   var bigInteger = BigInteger.Parse(guidBytes, NumberStyles.HexNumber);
   return bigInteger.ToString("N0", CultureInfo.InvariantCulture);
}


As Victor Derks pointed out in his answer, you should append a 00 byte to the end of the array to ensure the resulting BigInteger is positive.

According to the the BigInteger Structure (System.Numerics) MSDN Documentation:

To prevent the BigInteger(Byte[]) constructor from confusing the two's complement representation of a negative value with the sign and magnitude representation of a positive value, positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0.

(see also: byte[] to unsigned BigInteger?)

Here's code to do it:

var guid = Guid.NewGuid();
return String.Format("{0:N0}",
    new BigInteger(guid.ToByteArray().Concat(new byte[] { 0 }).ToArray()));


using System;
using System.Numerics;

Guid guid = Guid.NewGuid();
byte[] guidAsBytes = guid.ToByteArray();
BigInteger guidAsInt = new BigInteger(guidAsBytes);
string guidAsString = guidAsInt.ToString("N0");

Note that the byte order in the byte array reflects endian-ness of the GUID sub-components.


In the interest of brevity, you can accomplish the same work with one line of code:

string GuidToInteger = (new BigInteger(Guid.NewGuid().ToByteArray())).ToString("N0");

Keep in mind that .ToString("N0") is not "NO"... see the difference?

Enjoy

0

精彩评论

暂无评论...
验证码 换一张
取 消