用C#程式碼實現二進位制與十進位制的互相轉換

世紀緣發表於2016-10-07

程式碼如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Program
    {
        static void Main(string[] args)
        {
 
            int mark = 19;
            int tem = ToErJin(mark);
            Console.WriteLine("轉成二進位制後:" + tem);  // 列印“轉成二進位制後:10011”
 
            int mark2 = 10011;
            int tem2 = ToShijin(mark2);
            Console.WriteLine("轉成十進位制後:" + tem2);// 列印“轉成十進位制後:19”
        }
 
        /// <summary>
        /// 轉換為二進位制
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int ToErJin(int value)
        {
            int temp = 0;
            int shang = 1;
            int yushu;
            while (shang != 0)
            {
                shang = (int)value / 2;
                yushu = value % 2;
                value = shang;
                temp += yushu;
                if (shang != 0)
                {
                    temp = temp * 10;
                }
            }
            //最後將 temp 倒序
            string tempStr = temp.ToString();
            int tempLength = tempStr.Length;
            string resultStr = string.Empty;
            for (int i = 0; i < tempLength; i++)
            {
                resultStr = tempStr[i] + resultStr;
            }
            return int.Parse(resultStr);
        }
 
        /// <summary>
        /// 轉換為十進位制(主要演算法:個位數 * 2的零次方 + 十位數 * 2的一次方 + 百位數 * 2的二次方 + ...)
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int ToShijin2(int value)
        {
            int temp = 0;
            int shang = value;
            int yushu;
            int mark = 0;
            while (shang != 0)
            {
                yushu = shang % 10;
                shang = shang / 10;
                temp += yushu * (int)Math.Pow(2, mark);
                mark++;
            }
            return temp;
        }
 
        /// <summary>
        /// 二進位制轉十進位制的另一種方法(主要演算法:1110111 = 1 * 2~6 + 1 * 2~5 + 1 * 2~4 + 0 * 2~3 + 1 * 2~2 + 1 * 2~1 + 1 * 2~0)
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int ToShijin(int value)
        {
            string strValue = value.ToString();
            int valueLength = strValue.Length;
            int result = 0;
            for (int i = 0; i < valueLength; i++)
            {
                result += int.Parse(strValue[i].ToString()) * (int)Math.Pow(2, valueLength - 1 - i);
            }
            return result;
        }
    }

 

碼字不易,有幫助請點贊。

相關文章