简体   繁体   中英

How to use boost::uuids::uuid to convert to 128/64 bit numbers?

I use this code to produce UUIDs from boost:

boost::uuids::random_generator gen;
boost::uuids::uuid uuidId = gen();
string randomUUID = boost::lexical_cast<std::string>(uuidId);
std::remove( randomUUID.begin(), randomUUID.end(), '-');
randomUUID = "0x" + randomUUID;

It gives me hex numbers like: "0xCC5B9F6946EF4448A89EDB2042E0B084".

My question is: how convert this string (128 bit hex number) into 128 long long OR 64 bit long long (it it Ok to loose higher data)?

Standard C atoll and C++ std::stoll dont help in this case.

UUID prefered for random generation quality.

Thank you!

If all you want is a random 64bit unsigned integer then you can just use standard C++11:

std::mt19937_64 engine(std::random_device{}());
std::uniform_int_distribution<uint64_t> distribution;
auto ui64 = distribution(engine);

Live demo .

It works this way but the entropy needs research:

typedef unsigned long long ull;
//...
ull ui64 = 0;
const int startPosition = 18;//can vary - we can use rand() too
const int lengthHex = 14;//can vary - we can use rand() too
boost::uuids::random_generator gen;
boost::uuids::uuid uuidId = gen();
string randomUUID = boost::lexical_cast<std::string>(uuidId);
std::remove( randomUUID.begin(), randomUUID.end(), '-');
randomUUID = "0x" + randomUUID.substr(startPosition, lengthHex);
ui64 = std::stoull(randomUUID, 0, 16); //random out of UUID
std::cout << ui64 << '\n';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM