c语言itoa函数写法实现
时间: 2023-12-06 11:02:59 浏览: 84
以下是一个简单的itoa函数实现,供参考:
```c
char* itoa(int num, char* str, int base)
{
int i = 0;
bool isNegative = false;
if (num == 0) {
str[i++] = '0';
str[i] = '\0';
return str;
}
if (num < 0 && base == 10) {
isNegative = true;
num = -num;
}
while (num != 0) {
int rem = num % base;
str[i++] = (rem > 9) ? (rem - 10) + 'a' : rem + '0';
num /= base;
}
if (isNegative) {
str[i++] = '-';
}
str[i] = '\0';
// Reverse the string
int start = 0;
int end = i - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
return str;
}
```
这个函数可以将一个整数转化为任意进制的字符串,例如:
```c
char buffer[20];
itoa(123, buffer, 2); // 将123转化为二进制字符串
itoa(123, buffer, 8); // 将123转化为八进制字符串
itoa(123, buffer, 10); // 将123转化为十进制字符串
itoa(123, buffer, 16); // 将123转化为十六进制字符串
```
调用结束后,buffer中存放的就是相应进制下的字符串。
阅读全文