输入十进制以十六进制输出 (类似与c中的以%x输出)
程序员文章站
2022-07-15 09:07:57
...
eg:输入26输出a1;输入-1输出ffffffff
直接上代码,有注释
#include<stdio.h>
void Conversion(unsigned int n , char *str)//直接将num转化未unsigned类型,可以保证
{ //负数的正确输出
int i = 0;
while(n > 0)
{
if(n%16 < 10 )
{
str[i] = (n%16) + '0';//控制输出0-9
}
else
{
str[i] = (n%16) + 87;//控制输出a-f (ASCII表)
}
n = n>>4;
i++;
}
str[i] = '\0';
int j = i-1;
i = 0;
while(j > i)//交换顺序
{
str[i] ^= str[j];
str[j] ^= str[i];
str[i++] ^= str[j--];
}
}
char *toHex(int num)
{
char *s = (char*)malloc(9);
if(num == 0)//等于0
{
s[0] == '0';
s[1] == '\0';
}
else if(num > 0)//大于0
{
Conversion(num , s);
}
else if(num < 0)//小于0
{
Conversion((unsigned int) num, s);
}
return s;
}
int main()
{
int k = 0;
printf("please import k=");
scanf("%d",&k);
char *str = toHex(k);
printf("%s\n",str);
return 0;
}
上一篇: C语言学习