C# Program to Find Whether a Given Number is Power of 2 using Bitwise Operators

This is a C# Program to find power of 2 using bitwise operator.

Problem Description

This C# Program Finds Power of 2 using Bitwise Operator.

Problem Solution

Here Operations on bits at individual levels can be carried out using Bitwise operations and the whole representation of a number is considered while applying a bitwise operator.

Program/Source Code

Here is source code of the C# Program to Find Power of 2 using Bitwise Operator. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 *   C# Program to Find Power of 2 using Bitwise Operator
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
 
namespace example
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            int num;
            Console.Write("Enter a number:");
            num = Convert.ToInt32(Console.ReadLine());
            bool result = ((num & -num) == num);
            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}
Program Explanation

In this C# program, we are reading a number using ‘num’ variable. A bitwise operation is used to operations on bits at individual levels. The whole representation of a number is considered while applying a bitwise operator. Print the value of power of 2.

advertisement
advertisement
Runtime Test Cases
 
Enter a number:16
True

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.