Skip to content

Instantly share code, notes, and snippets.

@Noxwizard
Created January 20, 2019 03:42
Show Gist options
  • Save Noxwizard/b1ce4491f11df4fd1c72559904dc6258 to your computer and use it in GitHub Desktop.
Save Noxwizard/b1ce4491f11df4fd1c72559904dc6258 to your computer and use it in GitHub Desktop.
#if GCC_VERSION < 3004
/* Given X, an unsigned number, return the largest int Y such that 2**Y <= X.
If X is 0, return -1. */
int
floor_log2 (unsigned HOST_WIDE_INT x)
{
int t = 0;
if (x == 0)
return -1;
#ifdef CLZ_HWI
t = HOST_BITS_PER_WIDE_INT - 1 - (int) CLZ_HWI (x);
#else
if (HOST_BITS_PER_WIDE_INT > 64)
if (x >= (unsigned HOST_WIDE_INT) 1 << (t + 64))
t += 64;
if (HOST_BITS_PER_WIDE_INT > 32)
if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 32))
t += 32;
if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 16))
t += 16;
if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 8))
t += 8;
if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 4))
t += 4;
if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 2))
t += 2;
if (x >= ((unsigned HOST_WIDE_INT) 1) << (t + 1))
t += 1;
#endif
return t;
}
/* Return the logarithm of X, base 2, considering X unsigned,
if X is a power of 2. Otherwise, returns -1. */
int
exact_log2 (unsigned HOST_WIDE_INT x)
{
if (x != (x & -x))
return -1;
#ifdef CTZ_HWI
return x ? CTZ_HWI (x) : -1;
#else
return floor_log2 (x);
#endif
}
#endif /* GCC_VERSION < 3004 || !defined (__cplusplus) */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment