我需要生成一個10個字符的唯一編號(SIP/VOIP人們需要知道它是用於P-Charging-Vector標題中的參數icid值)。每個字符應該是26個ASCII字母之一(區分大小寫),10個ASCII字符之一或連字符減號。全球和本地唯一的10個字符的編號
它必須是「全球唯一的(產生id的機器之外的)'並且足夠'本地唯一的(在產生id的機器內)',並且所有需要被打包成10個字符,phew!
這是我的承擔。我首先編碼'必須'被編碼爲全局唯一的本地IP地址到base-63(它是一個無符號的long int,它將在編碼後佔用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[]="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-";
// 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;
}
「×[索引] =設定[LONGLONG%63];」已經搞亂了,看起來像「x [index] = set [longlongc];」 – Gaurav 2009-12-05 20:22:09