[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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章