Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Modern CPUs have a count-leading-zeros instruction to calculate floor(log2(x)) efficiently. GCC and clang expose this with the __builtin_clz* family of intrinsics. MSVC exposes this with _BitScanReverse.

  static inline uint64_t floor_log2(uint64_t x) {
      return 63 - __builtin_clzll(x);
  }


And C++ (as of C++20) exposes this and more in the header <bit>.

https://en.cppreference.com/w/cpp/header/bit




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: