Converting Between Binary and Decimal in C#
链接:http://www.csharphelp.com/archives4/archive694.html
From Decimal to Binary...
--------------------------------------------------------------------------------1using System;
2
3class Program{
4
5static void Main(string[] args){
6
7try{
8![]()
9int i = (int)Convert.ToInt64(args[0]);
10Console.WriteLine("\n{0} converted to Binary is {1}\n",i,ToBinary(i));
11![]()
12}catch(Exception e){
13![]()
14Console.WriteLine("\n{0}\n",e.Message);
15![]()
16}
17
18}//end Main
19
20
21public static string ToBinary(Int64 Decimal)
22{
23// Declare a few variables we're going to need
24Int64 BinaryHolder;
25char[] BinaryArray;
26string BinaryResult = "";
27
28while (Decimal > 0)
29{
30BinaryHolder = Decimal % 2;
31BinaryResult += BinaryHolder;
32Decimal = Decimal / 2;
33}
34
35// The algoritm gives us the binary number in reverse order (mirrored)
36// We store it in an array so that we can reverse it back to normal
37BinaryArray = BinaryResult.ToCharArray();
38Array.Reverse(BinaryArray);
39BinaryResult = new string(BinaryArray);
40
41return BinaryResult;
42}
43
44
45}//end class Program
46
From Binary to Decimal...
1using System;
2
3class Program{
4
5static void Main(string[] args){
6
7try{
8![]()
9int i = ToDecimal(args[0]);
10Console.WriteLine("\n{0} converted to Decimal is {1}",args[0],i);
11![]()
12}catch(Exception e){
13![]()
14Console.WriteLine("\n{0}\n",e.Message);
15![]()
16}
17
18}//end Main
19
20
21public static int ToDecimal(string bin)
22{
23long l = Convert.ToInt64(bin,2);
24int i = (int)l;
25return i;
26}
27
28
29}//end class Program
30
31