Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

c# - Binary to Decimal Conversion - Formula?

I've been searching a while and haven't gotten anything too useful yet, I'm working on a subnet calculator, and well I have used the decimal to binary which I found here, though, I haven't found a good way to convert binary to decimal.

Note: Remember its FROM binary TO decimal, anyways, im in need of the formula or something like that (meaning calculating it, not the automated one).

What I've understood by reading some other posts that you can somehow get the result by dividing by 10, but I didn't really understand it, so if anyone could point me in the right direction, I'd be glad.

Any and all help is very much appreciated guys! :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Doing it without LINQ:

var s = "101011";    // my binary "number" as a string
var dec = 0;
for( int i=0; i<s.Length; i++ ) {
  // we start with the least significant digit, and work our way to the left
  if( s[s.Length-i-1] == '0' ) continue;
  dec += (int)Math.Pow( 2, i );
}

A number in any base can be thought of as the sum of its digits multiplied by their place value. For example, the decimal number 3906 can be written as:

3*1000 + 9*100 + 0*10 + 6*1

The place values are simply powers of ten:

3*10^3 + 9*10^2 + 0*10^1 + 6*10^0

(Remember that any number taken to the power of zero is 1.)

Binary works exactly the same way, except the base is 2, not 10. For example, the binary number 101011 can be written as:

1*2^5 + 0*2^4 + 1*2^3 + 0*2^2 + 1*2^1 + 1*2^0

I hope that gives you a better understanding of binary numbers and how to convert them.

On a practical note, the best solution is Matt Grande's; it's always preferable to use a library method instead of rolling your own (unless you have a very good reason to do so).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...