Skip to content

Instantly share code, notes, and snippets.

@Harold2017
Forked from pps83/ctz_clz.cpp
Created May 4, 2022 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Harold2017/d490f5fef1525138cbefeb021900c124 to your computer and use it in GitHub Desktop.
Save Harold2017/d490f5fef1525138cbefeb021900c124 to your computer and use it in GitHub Desktop.
__builtin_ctz (ctzl, ctzll) and __builtin_clz (clzl, clzll) for Visual Studio
#ifdef _MSC_VER
#include <intrin.h>
static inline int __builtin_ctz(unsigned x) {
unsigned long ret;
_BitScanForward(&ret, x);
return (int)ret;
}
static inline int __builtin_ctzll(unsigned long long x) {
unsigned long ret;
_BitScanForward64(&ret, x);
return (int)ret;
}
static inline int __builtin_ctzl(unsigned long x) {
return sizeof(x) == 8 ? __builtin_ctzll(x) : __builtin_ctz((uint32_t)x);
}
static inline int __builtin_clz(unsigned x) {
//unsigned long ret;
//_BitScanReverse(&ret, x);
//return (int)(31 ^ ret);
return (int)__lzcnt(x);
}
static inline int __builtin_clzll(unsigned long long x) {
//unsigned long ret;
//_BitScanReverse64(&ret, x);
//return (int)(63 ^ ret);
return (int)__lzcnt64(x);
}
static inline int __builtin_clzl(unsigned long x) {
return sizeof(x) == 8 ? __builtin_clzll(x) : __builtin_clz((uint32_t)x);
}
#ifdef __cplusplus
static inline int __builtin_ctzl(unsigned long long x) {
return __builtin_ctzll(x);
}
static inline int __builtin_clzl(unsigned long long x) {
return __builtin_clzll(x);
}
#endif
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment