我目前遇到一个主要困难,试图让我的程序将二进制数转换为正确的十进制数。我拥有它给了我适当的数量,如111 = 7,但它给了我错误的数量,如1101 = 11,当它应该是13。
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int num;
//int n;
Console.WriteLine("Enter a number");
num = Convert.ToInt16(Console.ReadLine());
//n = num;
bintonum(num);
}
public static void bintonum (int num)
{
int dig;
double sum = 0;
while (num > 0)
{
dig = num % 10; //takes the number and breaks it down into each digit
sum = dig + (sum * 2); //reverses the number and adds the digit aquired from the previous line
num = num / 10; // reduces the number by one digit to get to zero
}
Console.WriteLine("{0}", sum);
}
}
}
答案 0 :(得分:2)
答案 1 :(得分:1)
如果你需要从基数2(二进制)到基数10(十进制),你可以使用这种方法:
111 2 = 1 * 2 ^ 2 + 1 * 2 ^ 1 + 1 * 2 ^ 0
...... = 4 + 2 + 1 = 7 10
1101 2 = 1 * 2 ^ 3 + 1 * 2 ^ 2 + 0 * 2 ^ 1 + 1 * 2 ^ 0
........ = 8 + 4 + 0 + 1 = 13 10
基本前提是二进制系统有两位数字,二进制数字中的每个占位符都可以乘以2的幂来得到它的十进制等值。对于十进制数字的位置也是如此:
121 10 = 1 * 10 ^ 2 + 2 * 10 ^ 1 + 1 * 10 ^ 0
......... = 100 + 20 + 1 = 121 10
2543 10 = 2 * 10 ^ 3 + 5 * 10 ^ 2 + 4 * 10 ^ 1 + 3 * 10 ^ 0
........... = 2000 + 500 + 40 + 3 = 2543 10
此外,您可以将此方法用于任何基数为10(十进制)。十六进制看起来像这样:
0 = 0, 1 = 1, 2 = 2, 3 = 3, 4 = 4, 5 = 5, 6 = 6, 7 = 7, 8 = 8,<登记/>
9 = 9, A = 10, B = 11, C = 12, D = 13, E = 14, F = 15
1A3C 16 = 1 * 16 ^ 3 + 10 * 16 ^ 2 + 3 * 16 ^ 1 + 12 * 16 ^ 0
............ = 4096 + 2560 + 48 + 12 = 6716 10
这是一个八进制示例:
八进制数系统的范围为0-7,通常用于表示三个二进制数的组
722 8 = 7 * 8 ^ 2 + 2 * 8 ^ 1 + 2 * 8 ^ 0
........ = 448 + 16 + 2 = 466 10
答案 2 :(得分:0)
当你正确检查'bit'(或第0位)时,你需要另一个循环,检查:
int num = 1101;
int sum = 0;
int n2 = 1;
while (num > 0)
{
int dig = num % 10;
sum = dig*n2 + sum;
num = num / 10;
n2 = n2 * 2;
}