Skip to content

Instantly share code, notes, and snippets.

@hsingtism
Created January 16, 2024 01:55
Show Gist options
  • Select an option

  • Save hsingtism/ca69ebd88477ed6ba6037ed7f553c27e to your computer and use it in GitHub Desktop.

Select an option

Save hsingtism/ca69ebd88477ed6ba6037ed7f553c27e to your computer and use it in GitHub Desktop.
mask a random 64 bit integer to a floating point range
/*
random64() is a random integer function
this code uses undefined behavior but it'll be alright
make sure to include stdint
*/
#include <stdint.h>
// mask to (-2,2]
// this is just an example, change the exponent bits for other ranges
inline double _22() {
uint64_t u64 = 0x4010000000000001ULL | (random64() >> 12);
return *(double *)&u64 - 6.0;
}
// mask to [0,1)
inline double _01() {
uint64_t u64 = 0x3FF0000000000000ULL | (random64() >> 12);
return *(double *)&u64 - 1.0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment