我需要生成一个 10 个字符的唯一 ID(SIP/VOIP 人员需要知道它用于 P-Charging-Vector 标头中的参数 icid 值)。每个字符应为 26 个 ASCII 字母之一(区分大小写)、10 个 ASCII 数字之一或连字符减号。
它必须是“全球唯一(在生成 id 的机器之外)”和足够“本地唯一(在生成 id 的机器内)”,所有这些都需要打包成 10 个字符,唷!
这是我的看法。我首先将“必须”编码为base-63(它是一个无符号长整数,编码后将占用1-6个字符),然后尽可能多地编码当前时间戳(它的一个 time_t/long long int 编码后将占用 9-4 个字符,具体取决于编码后的 ip 地址首先占用多少空间)。
我还在时间戳中添加了循环计数“i”以保持唯一性,以防在一秒钟内多次调用该函数。
这是否足以成为全球和本地独特的,还是有另一种更好的方法?
高拉夫
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
//base-63 character set
static char set[]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-";
// b63() returns the next vacant location in char array x
int b63(long long longlong,char *x,int index){
if(index > 9)
return index+1;
//printf("index=%d,longlong=%lld,longlong%63=%lld\n",index,longlong,longlong%63);
if(longlong < 63){
x[index] = set[longlong];
return index+1;
}
x[index] = set[longlong%63];
return b63(longlong/63,x,index+1);
}
int main(){
char x[11],y[11] = {0}; /* '\0' is taken care of here */
//let's generate 10 million ids
for(int i=0; i<10000000; i++){
/* add i to timestamp to take care of sub-second function calls,
3770168404(is a sample ip address in n/w byte order) = 84.52.184.224 */
b63((long long)time(NULL)+i,x,b63((long long)3770168404,x,0));
// reverse the char array to get proper base-63 output
for(int j=0,k=9; j<10; j++,k--)
y[j] = x[k];
printf("%s\n",y);
}
return 0;
}