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;
        }        
    }    
}

Leave A Reply

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

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...