Skip to content

Instantly share code, notes, and snippets.

@maurice-schuppe
Forked from fernandomv3/UUID.hpp
Created December 6, 2019 07:42
Show Gist options
  • Save maurice-schuppe/9b96f648806c4d57526a1fc085780536 to your computer and use it in GitHub Desktop.
Save maurice-schuppe/9b96f648806c4d57526a1fc085780536 to your computer and use it in GitHub Desktop.
C++ UUID generator
#ifndef UUID_H
#define UUID_H
#include <string>
#include <cstdlib>
//*Adapted from https://gist.github.com/ne-sachirou/882192
//*std::rand() can be replaced with other algorithms as Xorshift for better perfomance
//*Random seed must be initialized by user
namespace MathUtils{
const std::string CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
std::string generateUUID(){
std::string uuid = std::string(36,' ');
int rnd = 0;
int r = 0;
uuid[8] = '-';
uuid[13] = '-';
uuid[18] = '-';
uuid[23] = '-';
uuid[14] = '4';
for(int i=0;i<36;i++){
if (i != 8 && i != 13 && i != 18 && i != 14 && i != 23) {
if (rnd <= 0x02) {
rnd = 0x2000000 + (std::rand() * 0x1000000) | 0;
}
rnd >>= 4;
uuid[i] = CHARS[(i == 19) ? ((rnd & 0xf) & 0x3) | 0x8 : rnd & 0xf];
}
}
return uuid;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment