首页 > 解决方案 > 将 int 转换为加扰的 Guid 并返回

问题描述

我正在寻找一种将 int 转换为 Guid 的方法,但不让下一个与下一个连续。例如,我有这个:

static void Main(string[] args)
{
   var a = Int2Guid(1);
   var b = Int2Guid(2);
}

public static Guid Int2Guid(int value)
{
    byte[] bytes = new byte[16];
    BitConverter.GetBytes(value).CopyTo(bytes, 0);
    return new Guid(bytes);
}

public static int Guid2Int(Guid value)
{
    byte[] b = value.ToByteArray();
    int bint = BitConverter.ToInt32(b, 0);
    return bint;
}

这行得通,但我不希望数字是连续的,也不出现连续的。从上面的例子中,我得到a = {00000001-0000-0000-0000-000000000000}, 但是b = {00000002-0000-0000-0000-000000000000}。我想要类似的东西{48204b95-9cbb-4295-a6b1-cf05ebda9d0d}

有什么建议吗?

标签: c#guid

解决方案


对于 Guid 需要 4 个整数或 16 个字节,您应该输入 4 个整数或 16 个字节。

Int2Guid输入4个整数。

    public static Guid Int2Guid(int value, int value1, int value2, int value3)
    {
        byte[] bytes = new byte[16];
        BitConverter.GetBytes(value).CopyTo(bytes, 0);
        BitConverter.GetBytes(value1).CopyTo(bytes, 4);
        BitConverter.GetBytes(value2).CopyTo(bytes, 8);
        BitConverter.GetBytes(value3).CopyTo(bytes, 12);
        return new Guid(bytes);
    }

我将Guid2Int输出设为 int 数组。

    public static int[] Guid2Int(Guid value)
    {
        byte[] b = value.ToByteArray();
        int bint = BitConverter.ToInt32(b, 0);
        var bint1 = BitConverter.ToInt32(b, 4);
        var bint2 = BitConverter.ToInt32(b, 8);
        var bint3 = BitConverter.ToInt32(b, 12);
        return new[] {bint, bint1, bint2, bint3};
    }

当我创建一个 GuidInt2Guid并将其设置为时,Guid2Int它可以回到原点。

    static void Main(string[] args)
    {
        var guid = Guid.NewGuid();
        var foo = Guid2Int(guid);

        var a = Int2Guid(foo[0], foo[1], foo[2], foo[3]);

        Console.WriteLine(a == guid); //true
    }

我不知道你是否需要它。


推荐阅读