Code Golfing a “Is Power of Two?” Function

Instead of looping around, there’s a simpler way.

diff –git a/kernel/elf.cpp b/kernel/elf.cpp
index 8bee7c5..ca2d50c 100644
— a/kernel/elf.cpp
+++ b/kernel/elf.cpp
@@ -42,12 +42,9 @@
namespace Sortix {
namespace ELF {

-static bool is_power_of_two(uintptr_t value)
+static bool is_power_of_two(uintptr_t x)
{
– for ( uintptr_t i = 0; i < sizeof(uintptr_t) * 8; i++ )
– if ( (uintptr_t) 1 << i == value )
– return true;
– return false;
+ return (x != 0) && ((x & (x – 1)) == 0);
}

The code in question is found in the excellent hobby OS sortix.

Leave a Reply

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