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