C语言-十进制十六进制转换
目录
- 1.Rain_Conversion
- 2.Gali_Conversion
一个朋友提到十进制数转十六进制后以字符串输出,基于此写了两段代码以供参考,其中涉及数组成员反转,指针等特别基础的用法。仅娱乐。
1.Rain_Conversion
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "limits.h"
#define MAX_SIZE 100
int Conversion(long n,char *ret)
{
int remainder = 0;
char hex[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
int result[MAX_SIZE];
int i = 0;
char *rets =NULL;
memset(result,0x0,MAX_SIZE);
if(n==0){
*ret = '0';
return 0;
}
while(n>0){
remainder = n%16;
result[i++] = remainder;
n /= 16;
}
rets = ret;
for(i=i-1;i>=0;i--){
*ret = hex[result[i]];
ret++;
}
//*ret = '\0';
ret = rets;
return 0;
}
int main()
{
long a = 0;
char *ret = NULL;
ret = (char *)malloc(MAX_SIZE);
REPEAT:
printf("please input num %ld - %ld\n",LONG_MIN,LONG_MAX);
if( (scanf("%ld",&a) != 1)||(a<0) ){
puts("input err");
goto REPEAT;
}
if( !Conversion(a,ret) ){
printf("num a = %ld,ret = 0x%s\n",a,ret);
}
free(ret);
}
2.Gali_Conversion
-—————— 代码出自咖喱鸡
#include "stdio.h"
int main(void)
{
int j,re;
long int n;
int i = 0;
char str[100],ch;
puts("pleas input n(long int)");
scanf("%ld",&n);
while(n!=0){
re = n%16;
if( re>9 ){
str[i++] = (char)(re - 10) + 'a';
}else{
str[i++] = (char)re + '0';
}
n = n>>4;
}
str[i--] = '\0';
for(j=0;j<((i+1)>>1);j++){
ch = str[i-j];
str[i-j] = str[j];
str[j] = ch;
}
printf(" 0x%s\n",str);
}
还没有评论,来说两句吧...