Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save intrueder/d193655e19f64b209684 to your computer and use it in GitHub Desktop.
Save intrueder/d193655e19f64b209684 to your computer and use it in GitHub Desktop.
Generates random string in format of GUID (i.e. "{00000000-0000-0000-0000-000000000000}")
bool flipСoin()
{
bool side = false;
auto ms = std::chrono::high_resolution_clock::now() + std::chrono::microseconds(10);
while (std::chrono::high_resolution_clock::now() <= ms) side = !side;
return side;
}
unsigned char getRandomBit()
{
bool bit;
while (true)
{
bit = flipСoin();
if (bit != flipСoin())
return (unsigned char)bit;
}
return 0; // unreachable;
}
unsigned char getRandomByte()
{
unsigned char n = 0;
int bits = 8;
while (bits--)
{
n <<= 1;
n |= getRandomBit();
}
return n;
}
// string formatted like GUID, but it is random
std::wstring generateGuid()
{
std::wstringstream ss;
ss << L"{";
for (int i = 0; i < 16; i++)
{
if ((i & 0xC ^ 0xC) && (i & ~2) && !(i % 2)) ss << L'-';
ss << std::setfill(L'0') << std::setw(2) << std::hex << getRandomByte();
}
ss << L"}";
return ss.str();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment