Program to convert binary to decimal in C#? [duplicate]

扶醉桌前 提交于 2019-12-02 15:06:06
Duy

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!