For my homework, I need to write a program(in C#) that will convert any binary number into decimal. I can just use /,%, ,-,*, Idk how to do that? Please help me.
CodePudding user response:
If you want use bin
as a mask, e.g. for bin = 1010
1 0 1 0
x | | | |
8 4 2 1
--------
8 * 1 4 * 0 2 * 1 1 * 0 = 10
Code:
private static int MyConvert(int bin) {
int result = 0;
for (int factor = 1; bin > 0; bin /= 10, factor *= 2)
result = result bin % 10 * factor;
return result;
}
CodePudding user response:
Recursion can be your friend if "loops" aren't available to you:
public int BinaryToDecimal(int num) =>
BinaryToDecimal(num, 1);
private int BinaryToDecimal(int num, int factor) =>
num == 0 ? 0 : num % 10 * factor BinaryToDecimal(num / 10, factor * 2);
If I run this:
Console.WriteLine(BinaryToDecimal(1001));
I get 9
, as expected.
CodePudding user response:
Try this
public int BinaryToDecimal(int num)
{
int binary_num;
int decimal_num = 0, base = 1, rem;
binary_num = num; // assign the binary number to the binary_num variable
while ( num > 0)
{
rem = num % 10;
decimal_num = decimal_num rem * base;
num = num / 10; // divide the number with quotient
base = base * 2;
}
return decimal_num;
}