我想在Qt中创建v1 UUID(基于时间)
我尝试使用cppuuid但无法获得正确的uuid 我也试过ossp uuid但是在构建时遇到了错误,我宁愿避免使用它
我需要在Qt中生成此类uuid的最简单和最简短的方法(我更喜欢Qt类,如果有的话)
我希望v1 uuid将其用作我数据库中的主键
请参阅//https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/
我按照以下方式尝试了cppuuid
qulonglong v1 = 0x19432987;
qulonglong v2= 0x33;
uuid::Uuid u = uuid::uuid1( v1,v2 );
QByteArray uuid = QByteArray().append( QString::fromStdString( u.hex()));
qDebug() << "uuid size" << uuid.size(); // 25
qDebug() << "uuid" << uuid;
qDebug() << "uuid hex" << uuid.toHex();
qDebug() << "uuid hex size" << uuid.toHex().size(); //50
编辑:我发现为什么cppuuid会给出错误的结果,详细信息在我的回答中
答案 0 :(得分:1)
使用由本地随机数生成器播种的QUuid::createUuid
。你可以使用qsrand(time())
或类似的东西播种。
答案 1 :(得分:0)
我在cppuuid中发现了一个逻辑错误,导致了奇怪的结果。
cppuuid中的gettime函数如下:
static uint64_t gettime()
{
static uint64_t last_uuid_time = 0; // On the heap!
int rc = 0;
struct timespec tp;
uint64_t uuid_time = 0;
rc = clock_gettime(CLOCK_REALTIME, &tp);
// Convert to 100-nanosecond intervals
uuid_time = tp.tv_sec * 10000000;
uuid_time = uuid_time + (tp.tv_nsec / 100);
uuid_time = uuid_time + kNum_100nsec_1582_1970;
// If the clock looks like it went backwards, or is the same, increment it.
if (last_uuid_time <= uuid_time) {
uuid_time = last_uuid_time + 1;
}
last_uuid_time = uuid_time;
return uuid_time;
}
登录错误位于此 if condition
中 // If the clock looks like it went backwards, or is the same, increment it.
if (last_uuid_time <= uuid_time) {
uuid_time = last_uuid_time + 1;
}
&LT =
应该是
&GT; =
现在cppuuid正在给出正确的结果。希望这有帮助
uuid::Uuid u = uuid::uuid1(0x19432987, 0x33);
QByteArray uuid = QByteArray().append( QString::fromStdString( u.hex()));
qDebug() << "uuid size" << uuid.size(); // 32
qDebug() << "uuid" << uuid;