# The last man on Earth sat alone in a room…

This is what is supposed to be the shortest post on this blog.
Remember last post where I used __builtin_ctz to compute GCD? Well… Here’s a way to compute the log2 of an integer using another gcc builtin. Let me introduce __builtin_clz. clz stands for count leading zeroes. So this wonderful thing counts 0 bits starting from the most significant bit. Please note that the result is undefined for 0.

inline uint32_t ilog2(uint32_t i)
{
return (32-__builtin_clz(i));
}


Check the section 5.49 of GCC doc for more builtins.

By the way the title of this post comes from a short novel by Fredric Brown called Knock.

## 3 thoughts on “The last man on Earth sat alone in a room…”

1. Is that the solution used in math.h ?

2. Not at all. math.h only provides the floating point version.
If you want the gory details, here are the log2 code in glibc:

3. What a dumbass ! I should have noticed that math.h was about floating point version …

Is there any connection/similarities with the work done by Jörg Arndt ? ( http://www.jjj.de/fxt/ )