Implementation Challenge: A count leading zeroes function
When doing arithmetic in a programming language there is the arcane art of optimizing with the help of bit-wise operations. Of course I’m talking about Bit Hacks.
On a readability and maintainability ranking from 1 to awk Bit Hacks reach a level of Brainfuck.
Yet they can be an incredibly low-level optimization useful to tweak the last bit of performance out of an operation but are difficult to get right and 100% portable.
In this post we’ll take a look at a rather easy function - clz(x) that will return the number of leading zero bits in an unsigned integer type x.
In particular I’ll show you how to properly wrap GCC’s __builtin_clz().