[英]Converting Binaries in to Decimal number C#
For my homework, I need to write a program(in C#) that will convert any binary number into decimal.对于我的作业,我需要编写一个程序(在 C# 中)将任何二进制数转换为十进制。 I can just use /,%,+,-,*, Idk how to do that?我可以只使用 /,%,+,-,*, Idk 怎么做? Please help me.请帮我。
If you want use bin
as a mask , eg for bin = 1010
如果你想使用bin
作为掩码,例如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;
}
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.正如预期的那样,我得到9
。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.