Is Power of 2? (C#)

by Vitaly Zayko 13. March 2010 17:09

Continue playing with Integers. Here is how to determine if a number is power of 2 or not:

 /// <summary>
 /// Checks if an integer is power of 2
 /// </summary>
 /// <param name="i">An int number to check</param>
 /// <returns>true if i is power of 2, false if otherwise</returns>
 public static bool IsPower2(int i)
 {
     return (i != 0) && ((i & -i) == i);
 }
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Tags:

Code Snippets

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

About the author

Vitaly Zayko

Senior Software Developer / Team Lead / Product Manager

Moscow, Russia