-
Notifications
You must be signed in to change notification settings - Fork 62
Open
Description
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
Labels
No labels