itoa
char* itoa ( int value, char * str, int radix );
Detta är en funktion som ofta stöds av diverse kompilatorer men det är inte en standardfunktion i programmeringsspråken C eller C++. Den har som syfte att omvandla ett heltal till en sträng, i en viss bas. Så här står det om den och dess parametrar hos http://www.cplusplus.com:
Converts an integer value to a null-terminated string using the specified base and stores the result in the array given by str parameter. If base is 10 and value is negative, the resulting string is preceded with a minus sign (-). With any other base, value is always considered unsigned. str should be an array long enough to contain any possible value: (sizeof(int)*8+1) for radix=2, i.e. 17 bytes in 16-bits platforms and 33 in 32-bits platforms.
Parametrar:
- value
- Value to be converted to a string.
- str
- Array in memory where to store the resulting null-terminated string.
- radix
- Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary.
Returnerar: En pekare till en nollavslutad sträng, samma som parametern str.
Här följer en implementation av funktionen:
char* itoa(int value, char* string, int radix) { char tmp[33]; char *tp = tmp; int i; unsigned v; int sign; char *sp; if (radix > 36 || radix <= 1) { return 0; } sign = (radix == 10 && value < 0); if (sign) v = -value; else v = (unsigned)value; while (v || tp == tmp) { i = v % radix; v = v / radix; if (i < 10) *tp++ = i+'0'; else *tp++ = i + 'a' - 10; } if (string == 0) string = (char *)malloc((tp-tmp)+sign+1); sp = string; if (sign) *sp++ = '-'; while (tp > tmp) *sp++ = *--tp; *sp = 0; return string; }