用C++写一个十六进制转八进制
时间: 2023-05-27 22:07:57 浏览: 101
十六进制转八进制.cpp
```
#include <stdio.h>
#include <string.h>
int main() {
char hex[100];
int len, i, j, oct[100], k = 0;
printf("请输入一个十六进制数:");
scanf("%s", hex);
len = strlen(hex);
for (i = len - 1; i >= 0; i--) {
switch (hex[i]) {
case '0':
oct[k++] = 0;
oct[k++] = 0;
oct[k++] = 0;
oct[k++] = 0;
break;
case '1':
oct[k++] = 1;
oct[k++] = 0;
oct[k++] = 0;
oct[k++] = 0;
break;
case '2':
oct[k++] = 0;
oct[k++] = 1;
oct[k++] = 0;
oct[k++] = 0;
break;
case '3':
oct[k++] = 1;
oct[k++] = 1;
oct[k++] = 0;
oct[k++] = 0;
break;
case '4':
oct[k++] = 0;
oct[k++] = 0;
oct[k++] = 1;
oct[k++] = 0;
break;
case '5':
oct[k++] = 1;
oct[k++] = 0;
oct[k++] = 1;
oct[k++] = 0;
break;
case '6':
oct[k++] = 0;
oct[k++] = 1;
oct[k++] = 1;
oct[k++] = 0;
break;
case '7':
oct[k++] = 1;
oct[k++] = 1;
oct[k++] = 1;
oct[k++] = 0;
break;
case '8':
oct[k++] = 0;
oct[k++] = 0;
oct[k++] = 0;
oct[k++] = 1;
break;
case '9':
oct[k++] = 1;
oct[k++] = 0;
oct[k++] = 0;
oct[k++] = 1;
break;
case 'A':
case 'a':
oct[k++] = 0;
oct[k++] = 1;
oct[k++] = 0;
oct[k++] = 1;
break;
case 'B':
case 'b':
oct[k++] = 1;
oct[k++] = 1;
oct[k++] = 0;
oct[k++] = 1;
break;
case 'C':
case 'c':
oct[k++] = 0;
oct[k++] = 0;
oct[k++] = 1;
oct[k++] = 1;
break;
case 'D':
case 'd':
oct[k++] = 1;
oct[k++] = 0;
oct[k++] = 1;
oct[k++] = 1;
break;
case 'E':
case 'e':
oct[k++] = 0;
oct[k++] = 1;
oct[k++] = 1;
oct[k++] = 1;
break;
case 'F':
case 'f':
oct[k++] = 1;
oct[k++] = 1;
oct[k++] = 1;
oct[k++] = 1;
break;
default:
printf("输入的十六进制数有误!\n");
return 0;
}
}
printf("转换为八进制数为:");
if (k % 3 == 1) {
printf("%d", oct[0]);
for (i = 1; i < k; i += 3) {
printf("%d", oct[i] * 4 + oct[i + 1] * 2 + oct[i + 2]);
}
} else if (k % 3 == 2) {
printf("%d", oct[0] * 2 + oct[1]);
for (i = 2; i < k; i += 3) {
printf("%d", oct[i] * 4 + oct[i + 1] * 2 + oct[i + 2]);
}
} else {
for (i = 0; i < k; i += 3) {
printf("%d", oct[i] * 4 + oct[i + 1] * 2 + oct[i + 2]);
}
}
printf("\n");
return 0;
}
```
阅读全文