[英]How to create value generator ala hex in c#
I would like to create unique value generator that would work like this: I have 8 places for chars and it would create values like this: 我想创建一个像这样工作的唯一值生成器:我有8个char位置,它将创建像这样的值:
00000001 . 00000001。 0000000z .
0000000z。 00000010 .
00000010。 0000001z
0000001z
etc. so it would create values from 00000001 to zzzzzzzz. 等等,因此它将创建从00000001到zzzzzzzz的值。
I have only 8 places because this is the size of the field in the database and I can't change it. 我只有8个地方,因为这是数据库中字段的大小,我无法更改。
Thanks in advance 提前致谢
使用bultin random()函数,然后在完成后将结果转换为十六进制。
Are you sure you're not looking for a GUID? 您确定不是要寻找GUID吗?
Same number of chars, different structure: 550e8400-e29b-41d4-a716-446655440000 You can create a new GUID: 字符数相同,结构不同:550e8400-e29b-41d4-a716-446655440000您可以创建一个新的GUID:
System.Guid.NewGuid().ToString(""N"")
Split it every 8 chars and append a dot, like this: 每8个字符将其拆分并添加一个点,如下所示:
string getUnique()
{
char[] initial = System.Guid.NewGuid().ToString("N").ToCharArray();
string result="";
for(int i=0; i<initial.Count(); i++){
result=result + initial[i];
if((i+1)%4==0 && (i+1)!=initial.Count()){
result = result + ".";
}
}
return result;
}
something like this 像这样的东西
public class UniqueKeyMaker
{
private int[] keys = new int[8];
public void Reset()
{
for (int i = 0; i < keys.Length; i++)
keys[i] = 0;
}
public string NextKey()
{
string key = getCurrentKey();
increment();
return key;
}
private void increment()
{
int i = 7;
while (keys[i] == 35)
{
keys[i] = 0;
i--;
}
keys[i]++;
}
private string getCurrentKey()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 8; i++)
{
if (keys[i] < 10)
sb.Append((char)(keys[i] + (int)'0'));
else
sb.Append((char)(keys[i] - 10 + (int)'a'));
}
return sb.ToString();
}
}
You just want to encode an int into a base 36 system. 您只想将int编码为base 36系统。 This might work like like following(probably has a few small mistakes since it's notepad code):
这可能像下面这样工作(由于它是记事本代码,可能有一些小错误):
string IntToID(long id)
{
string result="";
Contract.Require(id>=0);
while(id>0)
{
int digit=id%36;
char digitChar;
if(digit<10)
digitChar='0'+digit;
else
digitChar='a'+(digit-10);
result+=digitChar;
id/=36;
}
result=result.PadLeft('0',8);
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.