C 语⾔,进制转换之⼗六进制转⼆进制,完整代码
#include "iostream"using namespace std;#define MAX 50int main()//⼗六转⼆{ int elem2[MAX]; char elem16[MAX]; cout << "请输⼊⼗六进制数,并以‘$’结束:"; int flag = 1; char ch; int i = 0; while (flag) { cin >> ch; if (ch != '$') { elem16[i] = ch; i++; } else { flag = 0; } } int length1 = i; int length2 = 0; int n = 0; int sum = 0; for (n = 0; n < length1; n++)//判断是否是⼗六进制数 { int x = (int )elem16[n]; if ((x >= 48 && x <= 57) || (x >= 65 && x <= 70)) sum++; } if (sum == length1) { int j = 0; int number = 0; int k = 0; int p = 0; int m = 0; int cout = 3; for (j = 0; j < length1; j++) { m = cout; int x = (int )elem16[j]; if (x >= 48 && x <= 57) { number = elem16[j] - 48; } else if (x >= 65 && x <= 70) { number = elem16[j] - 55; } if (number != 1) { do { elem2[m] = number % 2; number = number / 2; length2++;
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
length2++; k++; m--; } while (number>1); if (k == 3) { elem2[m] = 1; length2++; m--; } else { elem2[m] = 1; m--; length2++; for (p = 0; p < 3-k; p++) { elem2[m] = 0; length2++; m--; } } k = 0; } else { elem2[m] = 1; m--; length2++; for (p = 0; p < 3; p++) { elem2[m] = 0; length2++; m--; } } cout = cout + 4; } } else { cout << "输⼊的不是⼗六进制数!"; } cout << "正序输出:"; for (i = 0; i < length2; i++) cout << elem2[i] << " "; cout << endl; return 0;}6263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论