[C]3-5_itob

the C Proramme 3_5编程题
函数itob(n,s,b),将整数n转换为以b为底的数,并将转换结果以字符
形式保存到字符串中。如itob(n,s,16)把整数n格式化成十六进制数整数保存在s中 ;
思路:
求出n对应16进制形式(将十进制转16进制);
十六进制数保存到字符数组中;
字符数组进行翻转

完整程序链接,项目持续更新中,欢迎star

/*在s[]中保存整数n转换的字符串,使用数字b为底数*/
void itob(int n,char s[],int b){
	static char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	int i,sign;
	
	if(b<2 || b>36){
		fprintf(stderr,"EX3_5:Cannot support base %d\n",b);
		exit(EXIT_FAILURE);
	}
	
	if((sign = 0) < 0){	//将n变成正整数 
		n = -n;
	}
	do{
		s[i++] = digits[n%b];   //将n求余b的结果转换为十六进制 
	} while((n/=b) > 0);
	if(sign<0)
		s[i++] = '-';
	s[i] = '\0';
	reverse(s);	//翻转字符串 
} 

void reverse(char s[]){
	int c,i,j;
	for(i=0,j=strlen(s)-1;i<j;i++,j--){
		c = s[i];
		s[i] = s[j];
		s[j] = c;		
	}
}

输出结果

Decimal 255 in base 2 :11111111
Decimal 255 in base 3 :100110
Decimal 255 in base 4 :3333
Decimal 255 in base 5 :2010
Decimal 255 in base 6 :1103
Decimal 255 in base 7 :513
Decimal 255 in base 8 :377
Decimal 255 in base 9 :313
Decimal 255 in base 10:255
Decimal 255 in base 11:212
Decimal 255 in base 12:193
Decimal 255 in base 13:168
Decimal 255 in base 14:143
Decimal 255 in base 15:120
Decimal 255 in base 16:FF
Decimal 255 in base 17:F0
Decimal 255 in base 18:E3
Decimal 255 in base 19:D8
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值