itoa函数:要考虑进制问题
char * itoa(int number, char *dst, int radix)
-
- 参数有3个,int , char *, radix(进制)
- dst不能为NULL
- 进制有范围的,2<=radix<=16,否则不合法
- number有正负数之分的,对于不同的进制又不一样
如果number为正数,则不需要过多处理;
如果number为负数,则10进制要加'-'号,而其他进制不需要加符号位,而是把number的补码输出。 - 16进制的开始要有'0x',8进制的开始有'0',10进制的开始要有'-',其他进制无。
- 转换的方法:%radix /radix
- 字符串赋值时,要考虑进制的不同,如16进制有'A'~'F',如何赋值
- 结尾的'\0'别忘了
- 字符串最后要进行反转,反转的开始位置和结束位置要算好
代码实现:
#include <iostream>
#include <cstring>
#include <cassert>
using namespace std;
char * myitoa(int number, char *dst, int radix){
assert(dst != NULL);
if(radix < 2 || radix > 16){
return dst;
}
char *str = dst;
unsigned int temp;
if(number < 0 && radix == 10){
temp = (unsigned int)((-1)*number);
*str++ = '-';
}else{
temp = (unsigned int)number;
}
if(radix == 16){
*str++ = '0';
*str++ = 'x';
}else if(radix == 8){
*str++ = '0';
}
while(temp){
int i = temp % radix;
temp /= radix;
if(radix == 10 || radix == 8 || radix == 2){
*str++ = i + '0';
}
else if(radix == 16){
if(i > 9)
*str++ = i - 10 + 'A';
else
*str++ = i + '0';
}
}
*str = '\0';
// revert
int i=0;
if(radix == 16){
i += 2;
}else if(radix == 8){
i++;
}else if(radix == 10 && dst[0] == '-'){
i++;
}
int length = strlen(dst);
int end = (length - 1 + i) / 2;
for(int j = length -1; i <= end; ++i,--j){
int t = dst[i];
dst[i] = dst[j];
dst[j] = t;
}
return dst;
}
int main(){
int number = -123;
char str1[32];
char str2[32];
char str3[32];
char str4[32];
char str5[32];
myitoa(number, str1, 16);
cout << str1 << endl;
myitoa(number, str2, 10);
cout << str2 << endl;
myitoa(number, str3, 8);
cout << str3 << endl;
myitoa(number, str4, 2);
cout << str4 << endl;
myitoa(number, str5, 1);
cout << str5 << endl;
return 0;
}
输出:
0xFFFFFF85
-123
037777777605
11111111111111111111111110000101