Program to Convert Binary Number to Decimal and vice-versa - (C# Basic Programs)
Binary number system is an important topic in computer science and is widely used in programming. In this tutorial, we'll discuss a C# program to convert binary numbers to decimal and decimal numbers to binary.
Syntax
The syntax for converting a binary number to decimal in C# is:
int binary = 1010;
int decimal = Convert.ToInt32(binary.ToString(), 2);
The syntax for converting a decimal number to binary in C# is:
int decimal = 10;
string binary = Convert.ToString(decimal, 2);
Example
Binary to Decimal
using System;
namespace BinaryToDecimal
{
class Program
{
static void Main(string[] args)
{
int binary = 1010;
int decimal = Convert.ToInt32(binary.ToString(), 2);
Console.WriteLine("{0} in binary = {1} in decimal", binary, decimal);
}
}
}
Output:
1010 in binary = 10 in decimal
Decimal to Binary
using System;
namespace DecimalToBinary
{
class Program
{
static void Main(string[] args)
{
int decimal = 10;
string binary = Convert.ToString(decimal, 2);
Console.WriteLine("{0} in decimal = {1} in binary", decimal, binary);
}
}
}
Output:
10 in decimal = 1010 in binary
Explanation
To convert binary to decimal, we can use the Convert.ToInt32()
method and pass in the binary number as a string and 2
as the second parameter, indicating that the input is in base 2. The method then returns the decimal equivalent of the binary number.
To convert decimal to binary, we can use the Convert.ToString()
method and pass in the decimal number and 2
as the second parameter, indicating that the output should be in base 2. The method then returns the binary equivalent of the decimal number as a string.
Use
Binary to decimal and decimal to binary conversion is used extensively in programming, particularly in networking, cryptography, and computer graphics. Understanding how to convert between these two number systems is an essential part of being a programmer.
Summary
In this tutorial, we've discussed a C# program to convert binary numbers to decimal and decimal numbers to binary. We covered the syntax, examples, explanation, and use of binary to decimal and decimal to binary conversion. By understanding how to convert between these two number systems, programmers can work more effectively with binary data and perform calculations involving binary numbers.