How to Find if an Integer is a Power of 2 in C# ?

Do you want to know if an integer is a power of 2 in C# ? . Below is a simple method with the code snippet that lets you find if the given number is a power of 2 or not.

How to Find if an Integer is a Power of 2 in C# ?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ginktage
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            int InputValue = 16;
            bool value = IsPowerOf2(InputValue);
            Console.WriteLine(value);
            Console.ReadLine();
        }
        // How to Find if the integer is a Power of 2 ?
        private static bool IsPowerOf2(int InputValue)
        {
            bool value = (InputValue & (InputValue - 1)) == 0;
            return value;
        }        
    }    
}

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
Pin It

Leave a Reply

Your email address will not be published. Required fields are marked *