用C#代码实现二进制与十进制的互相转换
代码如下:
01 |
class Program |
02 |
{ |
03 |
static void Main(string[] args) |
04 |
{ |
05 |
|
06 |
int mark = 19; |
07 |
int tem = ToErJin(mark); |
08 |
Console.WriteLine("转成二进制后:" + tem); // 打印“转成二进制后:10011” |
09 |
|
10 |
int mark2 = 10011; |
11 |
int tem2 = ToShijin(mark2); |
12 |
Console.WriteLine("转成十进制后:" + tem2);// 打印“转成十进制后:19” |
13 |
} |
14 |
|
15 |
/// <summary> |
16 |
/// 转换为二进制 |
17 |
/// </summary> |
18 |
/// <param name="value"></param> |
19 |
/// <returns></returns> |
20 |
public static int ToErJin(int value) |
21 |
{ |
22 |
int temp = 0; |
23 |
int shang = 1; |
24 |
int yushu; |
25 |
while (shang != 0) |
26 |
{ |
27 |
shang = (int)value / 2; |
28 |
yushu = value % 2; |
29 |
value = shang; |
30 |
temp += yushu; |
31 |
if (shang != 0) |
32 |
{ |
33 |
temp = temp * 10; |
34 |
} |
35 |
} |
36 |
//最后将 temp 倒序 |
37 |
string tempStr = temp.ToString(); |
38 |
int tempLength = tempStr.Length; |
39 |
string resultStr = string.Empty; |
40 |
for (int i = 0; i < tempLength; i++) |
41 |
{ |
42 |
resultStr = tempStr[i] + resultStr; |
43 |
} |
44 |
return int.Parse(resultStr); |
45 |
} |
46 |
|
47 |
/// <summary> |
48 |
/// 转换为十进制(主要算法:个位数 * 2的零次方 + 十位数 * 2的一次方 + 百位数 * 2的二次方 + ...) |
49 |
/// </summary> |
50 |
/// <param name="value"></param> |
51 |
/// <returns></returns> |
52 |
public static int ToShijin2(int value) |
53 |
{ |
54 |
int temp = 0; |
55 |
int shang = value; |
56 |
int yushu; |
57 |
int mark = 0; |
58 |
while (shang != 0) |
59 |
{ |
60 |
yushu = shang % 10; |
61 |
shang = shang / 10; |
62 |
temp += yushu * (int)Math.Pow(2, mark); |
63 |
mark++; |
64 |
} |
65 |
return temp; |
66 |
} |
67 |
|
68 |
/// <summary> |
69 |
/// 二进制转十进制的另一种方法(主要算法:1110111 = 1 * 2~6 + 1 * 2~5 + 1 * 2~4 + 0 * 2~3 + 1 * 2~2 + 1 * 2~1 + 1 * 2~0) |
70 |
/// </summary> |
71 |
/// <param name="value"></param> |
72 |
/// <returns></returns> |
73 |
public static int ToShijin(int value) |
74 |
{ |
75 |
string strValue = value.ToString(); |
76 |
int valueLength = strValue.Length; |
77 |
int result = 0; |
78 |
for (int i = 0; i < valueLength; i++) |
79 |
{ |
80 |
result += int.Parse(strValue[i].ToString()) * (int)Math.Pow(2, valueLength - 1 - i); |
81 |
} |
82 |
return result; |
83 |
} |
84 |
} |
谢谢阅读!
浙公网安备 33010602011771号