C# program to convert a decimal number into a binary number

Here, we are going to learn how to convert a decimal number into a binary number in C#?
Submitted by Nidhi, on September 12, 2020

Here we will read a decimal number and then convert it into a corresponding binary number.

Program:

The source code to convert a decimal number to the binary number is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# program to convert a decimal number to the binary number

using System;

class Program
{
    static void Main(string[] args)
    {
        int decNum  =   0;
        int binNum  =   0;
        
        string tempRem = "";
        
        Console.Write("Enter a decimal number : ");
        decNum = int.Parse(Console.ReadLine());

        while (decNum >= 1)
        {
            tempRem += (decNum % 2).ToString();
            decNum = decNum / 2;
        }

        for (int i = tempRem.Length - 1; i >= 0; i--)
        {
            binNum = binNum*10 + tempRem[i]-0x30;
        }

        Console.WriteLine("Binary Number: "+binNum);
    }
}

Output:

Enter a decimal number : 9
Binary Number: 1001
Press any key to continue . . .

Explanation:

In the above program, we create a class Program that contains the Main() method, In the Main() method we read a decimal number from user input and then convert the decimal number into a corresponding binary number.

while (decNum >= 1)
{
    tempRem += (decNum % 2).ToString();
    decNum = decNum / 2;
}

In the above code, we find the remainder of the decimal number after dividing by 2 and then concatenated into the string.

for (int i = tempRem.Length - 1; i >= 0; i--)
{
    binNum = binNum*10 + tempRem[i]-0x30;
}

In the above code, we reversed the remainder string and covert the into the integer number and then print the result on the console screen.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.