吾爱程序员:这里有好玩的游戏和软件
当前位置:首页C语言教程 → C语言实现你自己的 itoa()

C语言实现你自己的 itoa()

来源:网络 | 更新时间:2022-01-30 08:58:00
itoa函数将整数转换为以空字符结尾的字符串。它也可以转换负数。itoa 函数的标准定义如下:- 
char* itoa(int num, char* buffer, int base)
第三个参数base指定转换基数。例如:- 如果 base 为 2,则它将整数转换为其二进制兼容字符串,或者如果 base 为 16,则它将创建整数的十六进制转换字符串形式。  如果 base 为 10 且 value 为负数,则生成的字符串前面有一个减号 (-)。对于任何其他基数,值总是被认为是无符号的。 参考:http ://www.cplusplus.com/reference/cstdlib/itoa/?kw=itoa 示例: 
  itoa(1567, str, 10) 应该返回字符串“1567”
  itoa(-1567, str, 10) 应该返回字符串“-1567”
  itoa(1567, str, 2) 应该返回字符串“11000011111”
  itoa(1567, str, 16) 应该返回字符串“61f”
必须处理给定数字的各个数字,并且必须将其对应的字符放入给定的字符串中。使用给定基数的重复除法,我们得到从最低有效位到最高有效位的各个数字。但在输出中,这些数字需要以相反的顺序排列。因此,我们将反复除法后得到的字符串反转并返回。

/* A C++ program to implement itoa() */
#include <iostream>
using namespace std;

/* A utility function to reverse a string */
void reverse(char str[], int length)
{
int start = 0;
int end = length -1;
while (start < end)
{
swap(*(str+start), *(str+end));
start++;
end--;
}
}

// Implementation of itoa()
char* itoa(int num, char* str, int base)
{
int i = 0;
bool isNegative = false;

/* Handle 0 explicitly, otherwise empty string is printed for 0 */
if (num == 0)
{
str[i++] = '0';
str[i] = '';
return str;
}

// In standard itoa(), negative numbers are handled only with
// base 10. Otherwise numbers are considered unsigned.
if (num < 0 && base == 10)
{
isNegative = true;
num = -num;
}

// Process individual digits
while (num != 0)
{
int rem = num % base;
str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0';
num = num/base;
}

// If number is negative, append '-'
if (isNegative)
str[i++] = '-';

str[i] = ''; // Append string terminator

// Reverse the string
reverse(str, i);

return str;
}

// Driver program to test implementation of itoa()
int main()
{
char str[100];
cout << "Base:10 " << itoa(1567, str, 10) << endl;
cout << "Base:10 " << itoa(-1567, str, 10) << endl;
cout << "Base:2 " << itoa(1567, str, 2) << endl;
cout << "Base:8 " << itoa(1567, str, 8) << endl;
cout << "Base:16 " << itoa(1567, str, 16) << endl;
return 0;
}
输出: 
Base:10 1567
Base:10 -1567
Base:2 11000011111
Base:8 3037
Base:16 61f

最新文章

热点资讯

手游排行榜

CopyRight 2020-2030吾爱程序员

鄂ICP备2021004581号-8

本站资源收集于网络,如有侵权请联系我们:35492删除0109@qq.com