我们有一个遗留的要求,即将现在新迁移的intID值存储到一个guid类型中,以便在ID不可知的数据类型上使用(基本上是利用"全局唯一"部分的旧代码,guid以便在一列中包含所有可能的ID /领域).
由于这个要求,有一个后续要求guid,以人类可读的方式嵌入entites的整数ID .这很重要,目前正在阻止我直接处理字节值.
目前,我有以下内容:
public static byte[] IntAsHexBytes(int value)
{
return BitConverter.GetBytes(Convert.ToInt64(value.ToString(), 16));
}
public static Guid EmbedInteger(int id)
{
var ib = IntAsHexBytes(id);
return new Guid(new byte[]
{
0,0,0,0,0,0,1,64,ib[7],ib[6],ib[5],ib[4],ib[3],ib[2],ib[1],ib[0]
});
}
Run Code Online (Sandbox Code Playgroud)
它把的视觉表示int为十六进制值(value.ToString()),转换其为long(Convert.ToInt64(value.ToString(), 16))和抓斗从字节long展平为byte[]用于创建guid在一个特定的结构.
所以给予int的42,当你把42作为一个十六进制和转换是到long你66,和上的66字节给出,将成为guid给:
"00000000-0000-4001-0000-000000000042"
Run Code Online (Sandbox Code Playgroud)
和int中379932126得出:
"00000000-0000-4001-0000-000379932126"
Run Code Online (Sandbox Code Playgroud)
因此最终结果是将整数放入guid最后12位数中,因此它在视觉上看起来像整数42(即使基础整数值为66).
这比使用连接构造字符串快大约30%-40%以便提供给new Guid(string)构造函数,但我觉得我错过了避免必须首先对字符串做任何事情的解决方案.
所涉及的实际时间非常小,因此性能提升可能无法证明这一努力的合理性.
这纯粹是为了我自己的好奇心,看看是否有更快的方法来解决这个问题.我发布在这里,因为我是一个长期以来的SO用户,但是我对这是否是代码审查问题感到沮丧,尽管我不是直接要求任何反对我的代码,它只是演示了我的内容想要作为输出.
提供的整数范围是0到int.MaxValue.
更新:为了完整性,这是我们目前拥有的以及我正在测试的内容:
string s = string.Format("00000000-0000-4001-0000-{0:D12}", id);
return new Guid(s);
Run Code Online (Sandbox Code Playgroud)
我上面的其他代码比这快30%左右.
好的,这是另一个完全避免字符串的版本。希望这可能会更好。:)
public static Guid EmbedInteger(int id)
{
byte[] bytes = new byte[8];
int i = 0;
while (id > 0)
{
int remainder = id%100;
bytes[i++] = (byte)(16*(remainder/10) + remainder%10);
id /= 100;
}
return new Guid(0, 0, 0x4001, bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]);
}
Run Code Online (Sandbox Code Playgroud)
Adam Houldsworth:更新:此代码也可以展开:
int remainder = id % 100;
bytes[0] = (byte)(16 * (remainder / 10) + remainder % 10);
id /= 100;
if (id == 0) return;
remainder = id % 100;
bytes[1] = (byte)(16 * (remainder / 10) + remainder % 10);
id /= 100;
if (id == 0) return;
remainder = id % 100;
bytes[2] = (byte)(16 * (remainder / 10) + remainder % 10);
id /= 100;
if (id == 0) return;
remainder = id % 100;
bytes[3] = (byte)(16 * (remainder / 10) + remainder % 10);
id /= 100;
if (id == 0) return;
remainder = id % 100;
bytes[4] = (byte)(16 * (remainder / 10) + remainder % 10);
Run Code Online (Sandbox Code Playgroud)