用C++设计一个程序,输入一个十进制整数,输出相应的十六进制数。设计一个函数实现数制转换。

2024-11-12 11:37:30
推荐回答(3个)
回答1:

 

 

代码文本:

char d[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
void convertDecimal2Hex(int num, char* szHex){
 szHex[0]=d[(unsigned)(num&0x0000000F)];
 szHex[1]=d[(unsigned)(num&0x000000F0>>1*4)];
 szHex[2]=d[(unsigned)(num&0x00000F00>>2*4)];
 szHex[3]=d[(unsigned)(num&0x0000F000>>3*4)];
 szHex[4]=d[(unsigned)(num&0x000F0000>>4*4)];
 szHex[5]=d[(unsigned)(num&0x00F00000>>5*4)];
 szHex[6]=d[(unsigned)(num&0x0F000000>>6*4)];
 szHex[7]=d[(unsigned)(num&0xF0000000>>7*4)];
 szHex[8]='\0';
}

void main(){
 char szHex[9];
 convertDecimal2Hex(34555, szHex);
 printf("%s", szHex);
}

思路如此,请自己测试,convertDecimal2Hex中的逻辑可以改为循环。

回答2:

你这里16进制的结果是要返回输出还是只输出?
只输出的话,我会这么做
void MyFunction(int interg){
printf("%x",interg);
}
需要返回值的话
char* MyFunction(int interg, char * head){

char* step1 = malloc(16);
int i, j, temp;

//第一步,逐层求余
for(i = 0; interg != 0; i++){
temp = interg % 16;
interg = interg / 16;
if(temp >9){
*(step1 + i) = (char)(temp + 55); //10~15转换成A(65)~F(..)ASCii码
}else{
*(step1 + i) = (char)(temp + 48); //同上
}
}
*(step1 + i--) = '\0';

//第二步,逆序转存
for(j = 0; i >= 0; j++, i--){
*(head + j) = *(step1 + i);
}
*(head + j) = '\0';

free(step1);
return head;
}

回答3:

#include "stdio.h"
void tran(int x,char b[])
{
char a[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int i,j;
for(i=3;i>=0;i--)
{
j=x%16;
x=(x-j)/16;
b[i]=a[j];
}
b[4]='\0';
}
void main()
{
int n;
char s[5];
printf("Input a number:");
scanf("%d",&n);
tran(n,s);
printf("%d=%s",n,s);
}