不使用uuid库,如何实现一个生成uuid的函数?

clever101
博客专家认证
2020-10-27 10:55:44
大家好,如题,不使用uuid库,如何实现一个生成uuid函数? 我从网上找了一个,貌似有问题,代码如下:


/**
* Create random UUID
*
* @param buf - buffer to be filled with the uuid string
*/

static char *random_uuid(char buf[37])
{
const char *c = "89ab";
char *p = buf;
int n;
for (n = 0; n < 16; ++n)
{
int b = rand() % 255;
switch (n)
{
case 6:
sprintf(p, "4%x", b % 15);
break;
case 8:
sprintf(p, "%c%x", c[rand() % strlen(c)], b % 15);
break;
default:
sprintf(p, "%02x", b);
break;
}

p += 2;
switch (n)
{
case 3:
case 5:
case 7:
case 9:
*p++ = '-';
break;
}
}
*p = 0;
return buf;
}

// 调用函数
void Test()
{
char buf[37] = { 0 };
random_uuid(buf);
}

...全文
26019 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
RedWolf1999 2020-11-02
  • 打赏
  • 举报
回复
不要重新发明车轮,直接读 /proc/sys/kernel/random/uuid 吧。

23,125

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧