An instance of an itoa function implemented in the C language
- 2020-06-01 10:26:26
- OfStack
An instance of an itoa function implemented in the C language
1. The prototype:
char *itoa( int value, char *string,int radix);
2. Function description:
value: data to be converted. string: the address of the destination string. radix: the converted base number, which can be 10, 16, etc.3. Simple implementation of the function:
#include <iostream>
#include <string>
using namespace std;
char* My_itoa(int value,char str[],int radix)
{
char temp[33];
char *tp = temp;
int i;
unsigned v;
int sign;
char *sp;
if(radix > 36 || radix < 1)
return 0;
sign = (radix == 10 && value < 0); //10 Hexadecimal negative
if(sign)
v = -value;
else
v = (unsigned)value;
while(v || tp == temp) // Into operation
{
i = v % radix;
v = v / radix;
if(i < 10)
*tp++ = i + '0';
else
*tp++ = i + 'a' - 10;
}
if(str == 0)
str = (char*)malloc((tp - temp) + sign + 1);
sp = str;
if(sign) // If it's a negative number, I'm going to put the minus sign into the array first
*sp++ = '-';
while(tp > temp)
*sp++ = *--tp;
*sp = 0;
return str;
}
int main()
{
long int num;
int radix; // The decimal representation of the input
char str[256];
cout<<" Please enter integers and base Numbers: ";
cin>>num>>radix;
My_itoa(num,str,radix);
cout<<" After the integer is converted to a string: ";
cout<<str<<endl;
return 0;
}
If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!