Number System Program in C#(sharp)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NumberSystem
{
class Program
{
static void Main(string[] args)
{
/*
* we are using the if condition to check all numbers are 0 or 1.
* conveting the string->integer->(base 2)->find binary number.
* usi .ToString("X"); for intege to hexdecimal value.
*/
string dec,binary;
Console.Write("Enter the Binary Number\t\t");
binary = Console.ReadLine();
int bin = Convert.ToInt32(binary);
bool status = true;
while (true)
{
if (bin == 0){break;}else{ int tmp = bin % 10;
if (tmp > 1){status = false;break;}bin = bin / 10;}
}
if (status == true)
{
dec = Convert.ToInt32(binary, 2).ToString();
Console.WriteLine("Decimal value\t\t\t{0}",dec);
string strHex = Convert.ToInt32(binary, 2).ToString("X");
Console.WriteLine("HexaDecimal value\t\t{0}", strHex);
}
else
{
Console.WriteLine("wrong input");
Console.ReadLine();
}
int num;
Console.Write("Enter the Decimal Number\t");
string m = Console.ReadLine();
bool isNum1 = int.TryParse(m, out num);
if (isNum1)
{
string ans = Convert.ToString(num, 2);
Console.WriteLine("Binary value\t\t\t{0}", ans);
string hexValue = num.ToString("X");
Console.WriteLine("HexaDecimal value\t\t{0}", hexValue);
}
else
{
Console.WriteLine("Wrong Input");
}
Console.Write("Enter the HexaDecimal Number\t");
string sw = Console.ReadLine();
bool isHex = sw.All("0123456789abcdefABCDEF".Contains);
if (isHex)
{
string result = Convert.ToString(Convert.ToInt32(sw, 16), 2).PadLeft(12, '0');
Console.WriteLine("Binary value =>\t\t{0}", result);
int decValue = Convert.ToInt32(sw, 16);
Console.WriteLine("Decimal values is\t{0}", decValue);
}
else
{
Console.Write("Wrong Input");
}
Console.ReadLine();
}
}
}

No comments:
Post a Comment