首页 > 代码库 > 十进制与二进制转换

十进制与二进制转换

用C#代码实现二进制与十进制的互相转换

代码如下:

 

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 = http://www.mamicode.com/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 = http://www.mamicode.com/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;
        }
    }