OLW: Validating Powers of 2

Whatever language you use (#Java, #C, #C++, #ObjectiveC, #Ruby, #Python, #Perl, #Javascript, #CSharp, etc), validating sizes is a common requirement in computer science. Here is a 1 liner that you can use in in almost any language to confirm that a number is a power of 2, which is common given computer architecture.

n&&(!(n&(n-1)))

“Why do they call it rush hour when nothing moves?” – Robin Williams

Advertisements

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