当前位置:网站首页>利用rand函数随机生成uuid
利用rand函数随机生成uuid
2022-08-11 05:16:00 【FussyCat】
- 利用rand()函数,产生的随机数,用来构造uuid。
- uuid格式为:
%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x - 特别说明:
必须要加上第17行的随机种子,才能产生随机数,否则,每次调用GenerateUuid(),获取到的uuid结果都是一样的值。
#include <string.h>
#include <string>
#include "time.h"
/* * 功能描述: 生成随机uuid * 参数描述: uuid字符串为36个字符加结束符,字符串长度为37 * * uuid 长度: 8 - 4 - 4 - 4 - 12 * uuid 格式:"%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x" * 字符 序号: 0~3 3 4~5 5 6~7 7 8~9 9 10~15 */
int generate_uuid(char buf[37])
{
const char *s = "89ab";
char *p = buf;
int pos;
srand((unsigned int) time(NULL)); // 加入随机种子
for(pos = 0; pos < 16; pos++) {
int randNum = rand();
int b = randNum % 255;
switch(pos) {
case 6:
sprintf(p, "4%x", b % 15);
break;
case 8:
sprintf(p, "%c%x", s[rand() % strlen(s)], b % 15);
break;
default:
sprintf(p, "%02x", b);
break;
}
p += 2;
switch(pos) {
case 3:
case 5:
case 7:
case 9:
*p++ = '-';
break;
}
}
*p = 0;
fprintf(stdout, "uuid: %s", buf);
return 0;
}


边栏推荐
猜你喜欢

【win10+cuda7.5+cudnn6.0安装caffe④】安装pycaffe

IDEA模板总结

Idea essential skills to improve work efficiency

更新啦~人生重开模拟器自制

flask框架学习:debug与配置项

Win10远程连接(实现多用户同时连接)

Linux中安装redis

(1) Docker installs Redis in practice (one master, two slaves, three sentinels)

flaks framework learning: adding variables to the URL

(3) Construction of a real-time performance monitoring platform (Grafana+Prometheus+Node_explorer+Jmeter)
随机推荐
0708作业---商品信息
imx6 yocto编译备忘
函数怎么用
Configure checkstyle in IDEA
The most complete installation tutorial of Pytorch (one step)
for循环使用多线程优化
pytorch和tensorflow函数对应表
更新啦~人生重开模拟器自制
课堂练习--0708
滴滴出行 nlp算法工程师面试经验分享 带offer截图真实
Blender 初教程
一张图带你解读--如何从零开始学习接口自动化
玩转mysql之查看mysql版本号
flaks framework learning: adding variables to the URL
让你代码越来越高大上的技巧——代码规范,你得知道
代理模式(简要介绍)
Pytorch最全安装教程(一步到位)
Flask framework learning: template inheritance
宝塔Linux环境下redis开启多端口
并发编程之线程基础