I'm currently experiencing a major difficulty trying to get my program to convert binary numbers into their proper decimal equivalent. With what I have it gives me the proper amount for some numbers like 111=7, but it gives me the wrong amount like 1101 = 11 when it is supposed to be 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);
}
}
}
This functionality is provided by the .NET framework:
Convert.ToInt32(num, 2)
Here, num
is the string, and 2
is the base in which the string is represented.
More details here .
If you need to go from base 2 (binary) to base 10 (decimal), you can use this approach:
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
The basic premise is that there are two digits for the binary system and every place holder in a binary number can be multiplied by a power of two to get its decimal equivalent. The same goes for places in a decimal number:
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
Also, you can use this approach for any base to base 10 (decimal). Hexadecimal looks like this:
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
Here is an octal example:
The octal number system ranges from 0-7 and is often used for representing groups of three of binary numbers.
722 8 = 7 *8^2 + 2 *8^1 + 2 *8^0
........ = 448 + 16 + 2 = 466 10
as you're checking right 'bit' (or 0th bit), you need another loop, check:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.