C语言-十进制十六进制转换


   一个朋友提到十进制数转十六进制后以字符串输出,基于此写了两段代码以供参考,其中涉及数组成员反转,指针等特别基础的用法。仅娱乐。


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);
}


  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值