Skip to content

Replace find_last_bit_set with some intrinsic functions #15

@wjcskqygj2015

Description

@wjcskqygj2015

In G++, there exists some intrinsic function that can make the function find_last_bit_set more efficiently, i.e. __builtin_clz
If under g++/clang, maybe we can replace the function like this. Or even simply using the BSR(bit scan reverse) instructions. Besides, the VSStudio also provides _BitScanReverse, _BitScanReverse64 if needed.

  template <typename T>
  constexpr unsigned find_last_bit_set(T val) {
    // Or we can replace it with bit scan reverse with extra 1 plus.
    if constexpr (sizeof(T) == sizeof(unsigned int)) {
      return sizeof(T) * 8 - __builtin_clz(val);
    } else if constexpr (sizeof(T) == sizeof(unsigned long)){
      return sizeof(T) * 8 - __builtin_clzl(val);
    } else if constexpr (sizeof(T) == sizeof(unsigned long long)){
      return sizeof(T) * 8 - __builtin_clzll(val);
    } else {
      unsigned result = 0;
      for (; val != 0; val >>= 1)
        ++result;
      return result;
    }
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions