简体   繁体   English

将 Guid 字符串转换为 BigInteger,反之亦然

[英]Convert a Guid string into BigInteger and vice versa

I can convert a Guid String into a BigInteger using method below.我可以使用下面的方法将 Guid 字符串转换为 BigInteger。 How can I convert BigInteger back to Guid string.如何将 BigInteger 转换回 Guid 字符串。

using System;
using System.Numerics;

class Class1
{       
    public static BigInteger GuidStringToBigInt(string guidString)
    {
        Guid g = new Guid(guidString);
        BigInteger bigInt = new BigInteger(g.ToByteArray());
        return bigInt;
    }

    static void Main(string[] args)
    {
        string guid1 = "{90f0fb85-0f80-4466-9b8c-2025949e2079}";

        Console.WriteLine(guid1);
        Console.WriteLine(GuidStringToBigInt(guid1));
        Console.ReadKey();
    }
}

Please check this: 请检查一下:

public static Guid ToGuid(BigInteger value)
{
     byte[] bytes = new byte[16];
     value.ToByteArray().CopyTo(bytes, 0);
     return new Guid(bytes);
}

Edit: Working Fiddle 编辑: 工作小提琴

If you want positive integer representations the conversion in the question and the reverse conversion in the accepted answer both don't work for all values.如果您想要正整数表示,问题中的转换和接受的答案中的反向转换都不适用于所有值。 For example, converting from ffffffff-ffff-ffff-ffff-ffffffffffff to a BigInteger will give -1 .例如,从ffffffff-ffff-ffff-ffff-ffffffffffff转换为 BigInteger 将得到-1 And converting from 340282366920938463463374607431768211455 to a Guid will give an exception.340282366920938463463374607431768211455转换为 Guid 会出现异常。

If you do want the positive representation (useful if you're trying to convert bases, for example) you'll need to add an additional byte with the value zero to the end of your byte array.如果您确实想要正数表示(例如,在尝试转换基数时很有用),则需要在字节数组的末尾添加一个值为 0 的附加字节。 (See this illustration for a positive values right before the frist "Remarks" section). (请参阅此插图以了解第一个“备注”部分之前的正值)。

public static BigInteger GuidStringToBigIntPositive(string guidString)
{
    Guid g = new Guid(guidString);
    var guidBytes = g.ToByteArray();
    // Pad extra 0x00 byte so value is handled as positive integer
    var positiveGuidBytes = new byte[guidBytes.Length + 1];
    Array.Copy(guidBytes, positiveGuidBytes, guidBytes.Length);

    BigInteger bigInt = new BigInteger(positiveGuidBytes);
    return bigInt;
}

public static string BigIntToGuidStringPositive(BigInteger bigint)
{
    // Allocate extra byte to store the large positive integer
    byte[] positiveBytes = new byte[17];
    bigint.ToByteArray().CopyTo(positiveBytes, 0);
    // Strip the extra byte so Guid can handle it
    byte[] bytes = new byte[16];
    Array.Copy(positiveBytes, bytes, bytes.Length);
    return new Guid(bytes).ToString();
}

Fiddle demonstrating both methods.小提琴演示这两种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM