【发布时间】:2020-02-18 09:49:00
【问题描述】:
基于on the specs,基于Cassandra's C++ driver source code,基于its struct definition,从EPOCH 开始从UUID 时间戳转换为秒似乎很容易。
但是,当我尝试这样做时,我总是得到错误的值。我做错了什么,我无法弄清楚它是什么。
为此,我使用了 here 和 here 提供的示例 UUID 值。
只需从 UUID 原始数据中取出第一个 uint64_t,屏蔽其前四个 MSb,减去一个差值并除以一个数字。
这是我的最小完整示例:
#include <boost/date_time.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <cstdint>
#include <iostream>
uint64_t TimestampFromUUID(const boost::uuids::uuid& uuid) {
static constexpr const int UUID_SIZE = 16;
static_assert(sizeof(uuid) == UUID_SIZE, "Invalid size of uuid");
static constexpr const int MS_FROM_100NS_FACTOR = 10000;
static constexpr const uint64_t OFFSET_FROM_15_10_1582_TO_EPOCH = 122192928000000000;
struct two64s {
uint64_t n1;
uint64_t n2;
} contents;
std::memcpy(&contents, uuid.data, UUID_SIZE);
// contents.n1 = __builtin_bswap64(contents.n1);
uint64_t timestamp = contents.n1 & UINT64_C(0x0FFFFFFFFFFFFFFF);
return (timestamp - OFFSET_FROM_15_10_1582_TO_EPOCH) / MS_FROM_100NS_FACTOR;
}
int main() {
std::cout << "Time now: " << (boost::posix_time::second_clock::universal_time() - boost::posix_time::ptime(boost::gregorian::date(1970, 1, 1))).total_milliseconds() << std::endl;
auto gen = boost::uuids::string_generator();
std::cout << "UUID: " << gen("49cbda60-961b-11e8-9854-134d5b3f9cf8") << std::endl;
std::cout << "Time from UUID: " << TimestampFromUUID(gen("49cbda60-961b-11e8-9854-134d5b3f9cf8")) << std::endl;
std::cout << "UUID: " << gen("58e0a7d7-eebc-11d8-9669-0800200c9a66") << std::endl;
std::cout << "Time from UUID: " << TimestampFromUUID(gen("58e0a7d7-eebc-11d8-9669-0800200c9a66")) << std::endl;
return 0;
}
这个程序的输出是:
Time now: 1571735685000
UUID: 49cbda60-961b-11e8-9854-134d5b3f9cf8
Time from UUID: 45908323159150
UUID: 58e0a7d7-eebc-11d8-9669-0800200c9a66
Time from UUID: 45926063291384
你可以玩这个源代码here。
为什么我的结果甚至不接近当前时间戳?我做错了什么?
【问题讨论】:
标签: c++ boost cassandra uuid boost-date-time