Skip to content

Instantly share code, notes, and snippets.

@Noxwizard
Created January 20, 2019 02:57
Show Gist options
  • Save Noxwizard/aa163a25a58e3b5f3359b77485a87139 to your computer and use it in GitHub Desktop.
Save Noxwizard/aa163a25a58e3b5f3359b77485a87139 to your computer and use it in GitHub Desktop.
#if GCC_VERSION < 3004
/* Return log2, or -1 if not exact. */
extern int exact_log2 (unsigned HOST_WIDE_INT);
/* Return floor of log2, with -1 for zero. */
extern int floor_log2 (unsigned HOST_WIDE_INT);
/* Inline versions of the above for speed. */
#else /* GCC_VERSION >= 3004 */
# if HOST_BITS_PER_WIDE_INT == HOST_BITS_PER_LONG
# define CLZ_HWI __builtin_clzl
# define CTZ_HWI __builtin_ctzl
# elif HOST_BITS_PER_WIDE_INT == HOST_BITS_PER_LONGLONG
# define CLZ_HWI __builtin_clzll
# define CTZ_HWI __builtin_ctzll
# else
# define CLZ_HWI __builtin_clz
# define CTZ_HWI __builtin_ctz
# endif
#ifndef floorlog2
#define floorlog2
inline int
floor_log2 (unsigned HOST_WIDE_INT x)
{
return x ? HOST_BITS_PER_WIDE_INT - 1 - (int) CLZ_HWI (x) : -1;
}
#endif
#ifndef exactlog2
#define exactlog2
inline int
exact_log2 (unsigned HOST_WIDE_INT x)
{
return x == (x & -x) && x ? (int) CTZ_HWI (x) : -1;
}
#endif
#endif /* GCC_VERSION >= 3004 */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment