Created
April 29, 2024 18:12
-
-
Save rfl890/46527b54ed627f0b0a0469282c3d321e to your computer and use it in GitHub Desktop.
Dice Roll with RDRAND
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdint.h> | |
#include <immintrin.h> | |
#ifdef __GNUC__ | |
#define LOG2(X) \ | |
((uint32_t)(8 * sizeof(unsigned long long) - __builtin_clzll((X)) - 1)) | |
#else | |
#ifdef _MSC_VER | |
#include <intrin.h> | |
inline uint32_t LOG2(uint64_t X) { | |
unsigned long out; | |
_BitScanReverse64(&out, X); | |
return out; | |
} | |
#endif | |
#endif | |
uint64_t get_closest_bitstring(uint64_t x) { | |
uint32_t bits = LOG2(x); | |
return ((uint64_t)1 << (bits + 1)) - 1; | |
} | |
uint64_t rdrand_random() { | |
uint64_t random; | |
while (!_rdrand64_step(&random)); | |
return random; | |
} | |
uint64_t diceroll(uint64_t sides) { | |
sides = sides - 1; | |
uint64_t bitstring = get_closest_bitstring(sides); | |
uint64_t random = rdrand_random() & bitstring; | |
while (random > sides) { | |
random = rdrand_random() & bitstring; | |
} | |
return random + 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment