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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...