How to convert from Decimal to Binary System in C#

This code below shows how you can convert a given Decimal number to the Binary number system. This is illustrated by using the Binary Right Shift Operator ">>".



using System;
using System.Text;
using System.Threading.Tasks;

namespace convert_decimal_to_binary
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, c, k;
            Console.WriteLine("Enter an integer in Decimal number system\n");
            n = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("\nBinary Equivalent is:\n");
            for (c = 31; c >= 0; c--)
            {
                k = n >> c;
                if (Convert.ToBoolean(k & 1))
                    Console.Write("1");
                else
                    Console.Write("0");
            }
            Console.ReadKey();
        }
    }

}
Custom Search