public string DecToBinConvert(string deci)
{
string output = null; //declare variable to store result
int reminderVal = 0; //declare variable to store the remainder
if (!IsNum(deci))// check the value to convert is numeric
{
Console.WriteLine("Not numeric!!! Enter value between 0 and 9");
}
else
{
int number = int.Parse(deci);// if numeric parse string to integer type
while (number > 0)
{
reminderVal = number % 2;//if numeric value>0, get reminder value by mod 2
number = number / 2; //get quotient value
output = reminderVal.ToString() + output;
}
}
return output;
}
private bool IsNum(string numVal)// function to check a value is numeric
{
bool answer = false;
try
{
int temp = int.Parse(numVal);
answer = true; // returns true if numeric
}
catch (Exception ex)
{
answer = false;// returns false if not numeric
}
return answer;
}
//For input value 5 convert to binary,
Output: 1010
//For input value 9.2 convert to binary,
Output: Not numeric!!! Enter value between 0 and 9
No comments:
Post a Comment