Skip to content

Instantly share code, notes, and snippets.

@rfl890
Last active April 29, 2024 18:08
Show Gist options
  • Save rfl890/f9a1f5997ed999b292e383516f6a9421 to your computer and use it in GitHub Desktop.
Save rfl890/f9a1f5997ed999b292e383516f6a9421 to your computer and use it in GitHub Desktop.
#include <stdint.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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment