This question already has an answer here:
- Binary to Decimal Conversion - Formula? 6 answers
I'm wanting to create a basic program to enable me to convert binary numbers into decimal numbers, but having looked almost everywhere on the internet, I just can't find a solution to this that works! I can't seem to follow the solutions, So far I've developed a bit of code, but not sure if it is correct or not, any help? Thanks
int iBinaryNum; //To store binary number
string sDecimalNum; //To store decimal numbers
Console.WriteLine("Enter the binary number you want to convert to decimal");
iBinaryNum = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The Binary number you have entered is " + iBinaryNum);
sDecimalNum = Convert.ToString(iBinaryNum, 2);
Console.WriteLine("This converted into decimal is " + sDecimalNum);
//Prevent program from closing
Console.WriteLine("Press any key to close");
Console.ReadKey();
The Convert.ToInt32 method has an overload which accepts a "from" base parameter. http://msdn.microsoft.com/en-us/library/1k20k614.aspx
iDecimalNum = Convert.ToInt32(binaryNumber, 2);
clearly you haven't looked hard enough How to convert binary to decimal
First, why do you use an int for the iBinaryNum?
Second, I would have put it in a string, and then rinse and repeat the following:
- have a counter, starting with 1
- take last digit, if it's 0, do nothing, if it's 1 multiply it by counter, add to temp result, multiply counter by 2.
- repeat with second from last ...
so, for 1010 , you'll have 0*1 + 1*2 +0*4 +1*8 = 10.
Here's another page : http://www.binaryhexconverter.com/binary-to-decimal-converter
Edit:
Well, to begin with, what you're asking for is for me to write your code.
All your really need is to figure out how to use loops (look here: http://csharp-station.com/Tutorial/CSharp/Lesson04 )
How to figure out the length of your string : string_name.Length
and then just run on your input from back to front (from length, down to 0), applying the algorithm.
If you really want to learn, follow the bread crumbs trail ...
If you just want someone to write your code ... well ... maybe someone else will ...
You shouldn't say you've looked every and couldn't find an answer. I understand you're new to this but a better phrase would be: 'I'm having trouble understanding the solutions I've found.'
Anyway, you can use an overload of ToInt32 to convert in a specified base.
iDecimalNum = Convert.ToInt32(iBinaryNum, 2);
Although, to do this, IDecimalNum needs to be a string. The edited code looks like this:
string iBinaryNum = Console.ReadLine();
int iDecimalNum = Convert.ToInt32(iBinaryNum, 2);
It's also a little weird that you want to convert to a decimal but store iDecimalNum as an integer.
See MSDN's documentation on the overload: http://msdn.microsoft.com/en-us/library/1k20k614(v=vs.110).aspx
来源:https://stackoverflow.com/questions/19967634/program-to-convert-binary-to-decimal-in-c