CLZ – The Integer Log Base 2 Instruction

In just a few CPU instructions, the truncated base 2 logarithm of any integer can be computed for any integer from -2^63 … 2^63 – 1. This has interesting applications in being able to rapidly access logarithmically increasing arrays. The Linux GCC compiler provides a built in function, __builtin_clzll, to allow this CPU instruction to be used directly from C and C++ on a 64 bit integer.

i              |  0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 15 | 16 | 31 | 32 
floor(log2(i)) | NA | 0 | 1 | 1 | 2 | 2 | 2 | 2 | 3 |  3 |  4 |  4 |  5
63 - clzll(i)  | ~1 | 0 | 1 | 1 | 2 | 2 | 2 | 2 | 3 |  3 |  4 |  4 |  5
Advertisements

About jimbelton

I'm a software developer, and a writer of both fiction and non-fiction, and I blog about movies, books, and philosophy. My interest in religious philosophy and the search for the truth inspires much of my writing.
This entry was posted in programming and tagged , , , , , , , . Bookmark the permalink.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s