Skip to content

Instantly share code, notes, and snippets.

@sailfish009
Forked from pps83/ctz_clz.cpp
Created April 20, 2019 08:22
Show Gist options
  • Select an option

  • Save sailfish009/bb4fd8e97ee32adabddc711ff2ca0eec to your computer and use it in GitHub Desktop.

Select an option

Save sailfish009/bb4fd8e97ee32adabddc711ff2ca0eec 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(uint32_t 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(uint32_t 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