大概思路:
输入任意十进制数字 首先确定位数;
使用整形数组来存储十六进制数; a[0] 表示十六进制数字的位数;
#include <stdio.h> #include <stdlib.h> #define MAXSIZE 10 int* ahex(int dec){ int n=1; int m=16; int *a; a = (int*)malloc(sizeof(int)*MAXSIZE+1); while(dec >= m) { m = m*16; n++; } //printf("位数:%d\n",n); *a = n; while(n>0) { *(a+n)= dec/(m/16); dec = dec-*(a+n)*(m/16); n--; m = m/16; } return a; } void print_hex(int *p){ int n = *p; printf("hex: 0x"); while(n>0) { switch(*(p+n)){ case 10:printf("A");break; case 11:printf("B");break; case 12:printf("C");break; case 13:printf("D");break; case 14:printf("E");break; case 15:printf("F");break; default: printf("%d",*(p+n));break; } n--; } printf("\n"); } int main() { int rec=0; int *p; while(1){ printf("请输入一个十进制数字:"); scanf("%d",&rec); p = ahex(rec); print_hex(p); } return 0; }
最终效果:
原文地址:https://www.cnblogs.com/tao-zhu-forever/p/9126890.html
时间: 2024-11-05 20:25:47