【问题标题】:Convert a Guid string into BigInteger and vice versa将 Guid 字符串转换为 BigInteger,反之亦然
【发布时间】:2019-01-24 19:05:01
【问题描述】:

我可以使用下面的方法将 Guid 字符串转换为 BigInteger。如何将 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();
    }
}

【问题讨论】:

    标签: c# guid biginteger


    【解决方案1】:

    请检查:

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

    编辑:Working Fiddle

    【讨论】:

    • 这太棒了!我想接受这个答案,但 Stack Overflow 说我必须等 2 分钟。大声笑。
    • 这是不正确的。尝试从一个到另一个 64bf6328-de36-48a1-af69-378183c37a00 抛出“GUID 的字节数组必须正好是 16 个字节长”这整个事情都很难闻。
    • 是的。对于@Will 提供的示例,它确实给出了“Guid 的字节数组必须恰好是 16 个字节长”。 @Simonare 有什么解决办法吗?
    • 没有明确的证据证明这是正确的,但它在几百万次重复中幸存下来。并不是说这对那里的大量向导有任何意义。
    • 是的!这个问题现在已经解决了。谢谢@Simonare!
    【解决方案2】:

    如果您想要正整数表示,则问题中的转换和已接受答案中的反向转换都不适用于所有值。例如,从 ffffffff-ffff-ffff-ffff-ffffffffffff 转换为 BigInteger 将得到 -1。从 340282366920938463463374607431768211455 转换为 Guid 会出现异常。

    如果您确实需要正表示(例如,在您尝试转换基时很有用),您需要在字节数组的末尾添加一个值为 0 的附加字节。 (看到这个 illustration for a positive values 就在第一个“备注”部分之前)。

    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 演示了这两种方法。

    【讨论】:

      猜你喜欢
      • 2011-05-27
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多