c# - 将 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}
。
有什么建议吗?
解决方案
对于 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
}
我不知道你是否需要它。
推荐阅读
- python-3.x - 列出目录和子目录的时间复杂度
- javascript - 通过 AJAX 向 NodeJS 服务器发送 POST 数据
- flutter - 寻找一种将任务列表项保存到 Flutter 中的设备或数据库的方法
- python - 在 Java 中压缩,在 Python 中解压缩 - snappy/redis-py-cluster
- redis - 使用 python-rq (redis) 在多台服务器上的远程工作人员
- c# - 按 3 列值 String.Length 排序
- php - 重写 .htaccess 导致 404
- elasticsearch - 带有分组查询字符串的 Elasticsearch
- r - 循环导致错误的位置/顺序
- flutter - Flutter:SingleChildScrollView 沿垂直轴收缩其子项错误