Source code in embedded C for unsigned integer to string - c

Without resorting to standard library utoa, I'm looking for source code of utoa so I may customise it for specific project. I have unsigned integer (32 bits) with output such as 0xFFFF_FFFF
I also looking for source code for unsigned integer and half word to string in binary format.

Try this:
char *dec(unsigned x, char *s)
{
*--s = 0;
if (!x) *--s = '0';
for (; x; x/=10) *--s = '0'+x%10;
return s;
}
You call it with a pointer to the end of a caller-provided buffer, and the function returns the pointer to the beginning of the string. The buffer should have length at least 3*sizeof(int)+1 to be safe.
Of course this is easily adapted to other bases.

Theres a lot of itoa source files easily found on google... That should give you what you want, eg. itoa from opensource.apple.com
Or write it from scratch, it's not too hard.

That's not terribly hard. Keep dividing by 10 and use the remainder mod 10 as an index into "0123455679". You build this up from right to left, so you have to buffer the result and return it in reverse:
char * utoa(unsigned int n)
{
char * res, buf[30]; // long enough for largest number
unsigned int i, counter = 0;
if (n == 0)
buf[counter++] = '0';
for ( ; n; n /= 10)
buf[counter++] = "0123456789"[n%10];
res = malloc(counter);
for (i = 0; i < counter; ++i)
res[i] = buf[counter - i - 1];
return res;
}

#include <stdint.h>
#include <string.h>
char * utox(uint32_t n) {
static char hexstr[sizeof(n)*2+1];
char * p = hexstr + sizeof(hexstr) -1;
int x;
memset(hexstr, '0', sizeof(hexstr));
*p-- = '\0';
while (n) {
x = n % 16;
if (x < 10)
*p-- = '0' + x;
else
*p-- = 'A' + x - 10;
n /= 16;
}
return hexstr;
}
This should do it, it zero pads. Simply changing the type of n in the function parameters will make it work for any integer type/size.

Most of the functions mentioned/suggested here uses modulus % operator, which is very expensive for embedded system.
So using divide by 10 idea is the only prominent option I guess. Here it is:
/*for byte which is 3 digit most*/
void itoa(unsigned char value,char *desitination)
{
desitination[0] = '\0';
desitination[1] = '\0';
desitination[2] = '\0';
desitination[3] = '\0';//you at least 4 char array, last char is NULL
while (value >= 100)
{
desitination[0]++;
value -= 100;
}
desitination[1] = '0';
while (value >= 10)
{
desitination[1]++;
value -= 10;
}
value+= '0';
desitination[2] =value;
}

There are many implementation of itoa. This is one of them which takes under consideration base from 2 to 36:
/**
* C++ version 0.4 char* style "itoa":
* Written by Lukás Chmela
* Released under GPLv3.
*/
char* itoa(int value, char* result, int base) {
// check that the base if valid
if (base < 2 || base > 36) { *result = '\0'; return result; }
char* ptr = result, *ptr1 = result, tmp_char;
int tmp_value;
do {
tmp_value = value;
value /= base;
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)];
} while ( value );
// Apply negative sign
if (tmp_value < 0) *ptr++ = '-';
*ptr-- = '\0';
while(ptr1 < ptr) {
tmp_char = *ptr;
*ptr--= *ptr1;
*ptr1++ = tmp_char;
}
return result;
}
More variations can be found here which includes speed performance of the various implementations.

Related

Parsing a string into an array of integers in C

So now that I've figured out how to get what I want, I'm just hoping somebody can let me know a cleaner, less ridiculous way of achieving the same thing. I'm just learning C. Here was my approach.
int main()
{
// String of positive and negative integer values
// Numbers are never more than 2 digits
char TEMPS[256] = "1 -22 -8 14 5";
int N = 5;
int ints[N];
int i = 0;
int mult;
// Arbitrary number to identify that num is not yet in use
int num = 999;
int c = 0;
mult = (TEMPS[c] != 45) ? -1 : 1;
while(strcmp(&TEMPS[c], "\0") != 0)
{
if(TEMPS[c] == 32)
{
ints[i] = mult * num;
i++;
num = 999;
mult = (TEMPS[c + 1] == 45) ? -1 : 1;
}
else if((TEMPS[c] != 45) && (TEMPS[c] != 32))
{
if(num == 999)
{
num = TEMPS[c] - '0';
}
else
{
num = num * 10 + (TEMPS[c] - '0');
}
}
c++;
}
ints[i] = mult * num;
}
I would use strtol - here's a good site for how it works and examples
http://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm
long int strtol(const char *str, char **endptr, int base)
Parameters
str -- This is the string containing the representation of an integral number.
endptr -- This is the reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
base -- This is the base, which must be between 2 and 36 inclusive, or be the special value 0.
Return Value
This function returns the converted integral number as a long int value, else zero value is r
I've included one example from the site.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[30] = "2030300 This is test";
char *ptr;
long ret;
ret = strtol(str, &ptr, 10);
printf("The number(unsigned long integer) is %ld\n", ret);
printf("String part is |%s|", ptr);
return(0);
}

Algorithm to parse an int from a string in one pass

I'm trying to write a function that parses an integer from a string representation.
My problem is that I don't know how to do this with one pass through the string. If I knew ahead of time that the input contained only characters in the range '0', '1', ..., '9' and that the string was of length n, I could of course calculate
character_1 * 10^(n-1) + character_2 * 10^(n-2) + .... + character_n * 10^0
but I want to deal with the general scenario as I've presented it.
I'm not looking for a library function, but an algorithm to achieve this in "pure C".
Here's the code I started from:
int parse_int (const char * c1, const char * c2, int * i)
{
/*
[c1, c2]: Range of characters in the string
i: Integer whose string representnation will be converted
Returns the number of characters parsed.
Exs. "2342kjsd32" returns 4, since the first 4 characters were parsed.
"hhsd3b23" returns 0
*/
int n = 0;
*i = 0;
while (c1!= c2)
{
char c = *c1;
if (c >= '0' && c <= '9')
{
}
}
return n;
}
Just as some of the comments and answers suggested, maybe a bit clearer: You have to "shift" the result "left" by multiplying it by 10 in every iteration before the addition of the new digit.
Indeed, this should remind us of Horner's method. As you have recognized, the result can be written like a polynomial:
result = c1 * 10^(n-1) + c2 * 10^(n-2) + ... + cn * 10^0
And this equation can be rewritten as this:
result = cn + 10*(... + 10*(c2 + 10*c1))
Which is the form this approach is based on. From the formula you can already see, that you don't need to know the power of 10 the first digit is to be multiplied by, directly from the start.
Here's an example:
#include <stdio.h>
int parse_int(const char * begin, const char * end, int * result) {
int d = 0;
for (*result = 0; begin != end; d++, begin++) {
int digit = *begin - '0';
if (digit >= 0 && digit < 10) {
*result *= 10;
*result += digit;
}
else break;
}
return d;
}
int main() {
char arr[] = "2342kjsd32";
int result;
int ndigits = parse_int(arr, arr+sizeof(arr), &result);
printf("%d digits parsed, got: %d\n", ndigits, result);
return 0;
}
The same can be achieved using sscanf(), for everyone that is fine with using the C standard library (can also handle negative numbers):
#include <stdio.h>
int main() {
char arr[] = "2342kjsd32";
int result, ndigits;
sscanf(arr, "%d%n", &result, &ndigits);
printf("%d digits parsed, got: %d\n", ndigits, result);
return 0;
}
The output is (both implementations):
$ gcc test.c && ./a.out
4 digits parsed, got: 2342
I think this is good solution to count parse character
int parse(char *str)
{
int k = 0;
while(*str)
{
if((*str >= '0') & (*str <= '9'))
break;
str++;
k++;
}
return k;
}
Here's a working version:
#include <stdio.h>
int parse_int (const char * c1, const char * c2, int * i)
{
/*
[c1, c2]: Range of characters in the string
i: Integer whose string representnation will be converted
Returns the number of characters parsed.
Exs. "2342kjsd32" returns 4, since the first 4 characters were parsed.
"hhsd3b23" returns 0
*/
int n = 0;
*i = 0;
for (; c1 != c2; c1++)
{
char c = *c1;
if (c >= '0' && c <= '9')
{
++n;
*i = *i * 10 + c - '0';
}
else
{
break;
}
}
return n;
}
int main()
{
int i;
char const* c1 = "2342kjsd32";
int n = parse_int(c1, c1+10, &i);
printf("n: %d, i: %d\n", n, i);
return 0;
}
Output:
n: 4, i: 2342

C conver unsigned char to HEX

is convert unsigned char / int to hex, trouble is no correct translate ascci table:
original: 0D, converted: AD
code:
char int_to_hex(int d) {
if (d < 0) return -1;
if (d > 16) return -1;
if (d <= 9) return '0' + d;
d -= 10;
return (char)('A' + d);
}
void uint_to_hex(unsigned char in, char **out, int *olen) {
int i = 0;
int remain[2];
int result = (int)in;
while (result) {
remain[i++] = result % 16;
result /= (int)16;
}
for (i = 1; i >= 0; --i) {
char c = int_to_hex(remain[i]);
if( (int)c == -1 ) { continue; }
*((*out) + (*olen)) = (char)c; (*olen)++;
}
}
where is incorrect ?..
First of all one hex digit will cover values from 0 (0) to 15 (F) not from 0 to 16 (as you seem to assume in int_to_hex function).
Also you don't really need typecasting to char in last return of that function.
In fact all typecasts here are rather unnecessary
And typecasting of literal 16 is purely absurd...
And how sample input for uint_to_hex is looking ? You are aware, that on input (in) you can pass only single character ?
I think that char pointer would suffice for out - i mean, you want to return array, right ?
So instead of ** should be only singe *.
And I don't understand why olen has to be pointer (and argument to function too).
And you should try to write more concise and readable code, it will help you understand what you are doing too.

Decimal to Binary on C library

I want to know if there is a function in C library that convert a decimal to binary number and save number by number in a position on an array.
For example: 2 -> 10 -> array [0] = 0 array[1] = 1.
Thanks.
here:
void dec2bin(int c)
{
int i = 0;
for(i = 31; i >= 0; i--){
if((c & (1 << i)) != 0){
printf("1");
}else{
printf("0");
}
}
}
But this only prints the value of an integer in binary format. All data is represented in binary format internally anyway.
You did not define what is a decimal number for you. I am guessing it is character representation (e.g. in ASCII) of that number.
Notice that numbers are just numbers. Binary or decimal numbers do not exist, but a given number may have a binary, and a decimal, representation. Numbers are not made of digits!
Then you probably want sscanf(3) or strtol(3) pr atoi to convert a string to an integer (e.g. an int or a long), and snprintf(3) to convert an integer to a string.
If you want to convert a number to a binary string (with only 0 or 1 char-s in it) you need to code that conversion by yourself. To convert a binary string to some long use strtol.
There is no such function in C standard library. Anyway, you can write your own:
void get_bin(int *dst, intmax_t x);
Where dst is the resulting array (with 1s and 0s), and x is the decimal number.
For example:
C89 version:
#include <limits.h>
void get_bin(int *dst, int x)
{
int i;
for (i = sizeof x * CHAR_BIT - 1; i >= 0; --i)
*dst++ = x >> i & 1;
}
C99 version:
/* C99 version */
#include <limits.h>
#include <stdint.h>
void get_bin(int *dst, intmax_t x)
{
for (intmax_t i = sizeof x * CHAR_BIT - 1; i >= 0; --i)
*dst++ = x >> i & 1;
}
It works as follow: we run through the binary representation of x, from left to right. The expression (sizeof x * CHAR_BIT - 1) give the number of bits of x - 1. Then, we get the value of each bit (*dst++ = x >> i & 1), and push it into the array.
Example of utilisation:
void get_bin(int *dst, int x)
{
int i;
for (i = sizeof x * CHAR_BIT - 1; i >= 0; --i)
*dst++ = x >> i & 1;
}
int main(void)
{
int buf[128]; /* binary number */
int n = 42; /* decimal number */
unsigned int i;
get_bin(buf, n);
for (i = 0; i < sizeof n * CHAR_BIT; ++i)
printf("%d", buf[i]);
return 0;
}
Here is a version that explicitly uses a string buffer:
#include <string.h>
const char *str2bin(int num, char buffer[], const int BUFLEN)
{
(void) memset(buffer, '\0', BUFLEN );
int i = BUFLEN - 1; /* Index into buffer, running backwards. */
int r = 0; /* Remainder. */
char *p = &buffer[i - 1]; /* buffer[i] holds string terminator '\0'. */
while (( i >= 0 ) && ( num > 0 )) {
r = num % 2;
num = num / 2;
*p = r + '0';
i--;
p--;
}
return (p+1);
}
Use char * itoa ( int value, char * str, int base );
Find more here ...
the function should go like this:
int dec2bin(int n){
static int bin,osn=1,c;
if(n==0) return 0;
else {
c=n%2;
bin += c*osn;
osn*=10;
dec2bin(n/2);
}
return bin;
}
As far as i know there is no such function in any C library. But here's a recursive function that returns a binary representation of a decimal number as int:
int dec2bin(int n)
{
if(n == 0) return 0;
return n % 2 + 10 * dec2bin(n / 2);
}
The max number that it can represent is 1023 (1111111111 in binary) because of int data type limit, but you can substitute int for long long data type to increase the range. Then, you can store the return value to array like this:
int array[100], i = 0;
int n = dec2bin(some_number);
do{
array[i] = n % 10;
n /= 10;
i++;
}while(n > 10)
I know this is an old post, but i hope this will still help somebody!
If it helps you can convert any decimal to binary using bitset library, for example:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main(){
int decimal = 20;
bitset<5> binary20(decimal);
cout << binary20 << endl;
return 0;
}
So, you have an output like 10100. Bitsets also have a "toString()" method for any purpose.

What is the proper way of implementing a good "itoa()" function?

I was wondering if my implementation of an "itoa" function is correct. Maybe you can help me getting it a bit more "correct", I'm pretty sure I'm missing something. (Maybe there is already a library doing the conversion the way I want it to do, but... couldn't find any)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char * itoa(int i) {
char * res = malloc(8*sizeof(int));
sprintf(res, "%d", i);
return res;
}
int main(int argc, char *argv[]) {
...
// Yet, another good itoa implementation
// returns: the length of the number string
int itoa(int value, char *sp, int radix)
{
char tmp[16];// be careful with the length of the buffer
char *tp = tmp;
int i;
unsigned v;
int sign = (radix == 10 && value < 0);
if (sign)
v = -value;
else
v = (unsigned)value;
while (v || tp == tmp)
{
i = v % radix;
v /= radix;
if (i < 10)
*tp++ = i+'0';
else
*tp++ = i + 'a' - 10;
}
int len = tp - tmp;
if (sign)
{
*sp++ = '-';
len++;
}
while (tp > tmp)
*sp++ = *--tp;
return len;
}
// Usage Example:
char int_str[15]; // be careful with the length of the buffer
int n = 56789;
int len = itoa(n,int_str,10);
The only actual error is that you don't check the return value of malloc for null.
The name itoa is kind of already taken for a function that's non-standard, but not that uncommon. It doesn't allocate memory, rather it writes to a buffer provided by the caller:
char *itoa(int value, char * str, int base);
If you don't want to rely on your platform having that, I would still advise following the pattern. String-handling functions which return newly allocated memory in C are generally more trouble than they're worth in the long run, because most of the time you end up doing further manipulation, and so you have to free lots of intermediate results. For example, compare:
void delete_temp_files() {
char filename[20];
strcpy(filename, "tmp_");
char *endptr = filename + strlen(filename);
for (int i = 0; i < 10; ++i) {
itoa(endptr, i, 10); // itoa doesn't allocate memory
unlink(filename);
}
}
vs.
void delete_temp_files() {
char filename[20];
strcpy(filename, "tmp_");
char *endptr = filename + strlen(filename);
for (int i = 0; i < 10; ++i) {
char *number = itoa(i, 10); // itoa allocates memory
strcpy(endptr, number);
free(number);
unlink(filename);
}
}
If you had reason to be especially concerned about performance (for instance if you're implementing a stdlib-style library including itoa), or if you were implementing bases that sprintf doesn't support, then you might consider not calling sprintf. But if you want a base 10 string, then your first instinct was right. There's absolutely nothing "incorrect" about the %d format specifier.
Here's a possible implementation of itoa, for base 10 only:
char *itobase10(char *buf, int value) {
sprintf(buf, "%d", value);
return buf;
}
Here's one which incorporates the snprintf-style approach to buffer lengths:
int itobase10n(char *buf, size_t sz, int value) {
return snprintf(buf, sz, "%d", value);
}
A good int to string or itoa() has these properties;
Works for all [INT_MIN...INT_MAX], base [2...36] without buffer overflow.
Does not assume int size.
Does not require 2's complement.
Does not require unsigned to have a greater positive range than int. In other words, does not use unsigned.
Allows use of '-' for negative numbers, even when base != 10.
Tailor the error handling as needed. (needs C99 or later):
char* itostr(char *dest, size_t size, int a, int base) {
// Max text needs occur with itostr(dest, size, INT_MIN, 2)
char buffer[sizeof a * CHAR_BIT + 1 + 1];
static const char digits[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (base < 2 || base > 36) {
fprintf(stderr, "Invalid base");
return NULL;
}
// Start filling from the end
char* p = &buffer[sizeof buffer - 1];
*p = '\0';
// Work with negative `int`
int an = a < 0 ? a : -a;
do {
*(--p) = digits[-(an % base)];
an /= base;
} while (an);
if (a < 0) {
*(--p) = '-';
}
size_t size_used = &buffer[sizeof(buffer)] - p;
if (size_used > size) {
fprintf(stderr, "Scant buffer %zu > %zu", size_used , size);
return NULL;
}
return memcpy(dest, p, size_used);
}
I think you are allocating perhaps too much memory. malloc(8*sizeof(int)) will give you 32 bytes on most machines, which is probably excessive for a text representation of an int.
i found an interesting resource dealing with several different issues with the itoa implementation
you might wanna look it up too
itoa() implementations with performance tests
I'm not quite sure where you get 8*sizeof(int) as the maximum possible number of characters -- ceil(8 / (log(10) / log(2))) yields a multiplier of 3*. Additionally, under C99 and some older POSIX platforms you can create an accurately-allocating version with sprintf():
char *
itoa(int i)
{
int n = snprintf(NULL, 0, "%d", i) + 1;
char *s = malloc(n);
if (s != NULL)
snprintf(s, n, "%d", i);
return s;
}
HTH
You should use a function in the printf family for this purpose. If you'll be writing the result to stdout or a file, use printf/fprintf. Otherwise, use snprintf with a buffer big enough to hold 3*sizeof(type)+2 bytes or more.
sprintf is quite slow, if performance matters it is probably not the best solution.
if the base argument is a power of 2 the conversion can be done with a shift and masking, and one can avoid reversing the string by recording the digits from the highest positions. For instance, something like this for base=16
int num_iter = sizeof(int) / 4;
const char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/* skip zeros in the highest positions */
int i = num_iter;
for (; i >= 0; i--)
{
int digit = (value >> (bits_per_digit*i)) & 15;
if ( digit > 0 ) break;
}
for (; i >= 0; i--)
{
int digit = (value >> (bits_per_digit*i)) & 15;
result[len++] = digits[digit];
}
For decimals there is a nice idea to use a static array big enough to record the numbers in the reversed order, see here
Integer-to-ASCII needs to convert data from a standard integer type
into an ASCII string.
All operations need to be performed using pointer arithmetic, not array indexing.
The number you wish to convert is passed in as a signed 32-bit integer.
You should be able to support bases 2 to 16 by specifying the integer value of the base you wish to convert to (base).
Copy the converted character string to the uint8_t* pointer passed in as a parameter (ptr).
The signed 32-bit number will have a maximum string size (Hint: Think base 2).
You must place a null terminator at the end of the converted c-string Function should return the length of the converted data (including a negative sign).
Example my_itoa(ptr, 1234, 10) should return an ASCII string length of 5 (including the null terminator).
This function needs to handle signed data.
You may not use any string functions or libraries.
.
uint8_t my_itoa(int32_t data, uint8_t *ptr, uint32_t base){
uint8_t cnt=0,sgnd=0;
uint8_t *tmp=calloc(32,sizeof(*tmp));
if(!tmp){exit(1);}
else{
for(int i=0;i<32;i++){
if(data<0){data=-data;sgnd=1;}
if(data!=0){
if(data%base<10){
*(tmp+i)=(data%base)+48;
data/=base;
}
else{
*(tmp+i)=(data%base)+55;
data/=base;
}
cnt++;
}
}
if(sgnd){*(tmp+cnt)=45;++cnt;}
}
my_reverse(tmp, cnt);
my_memcopy(tmp,ptr,cnt);
return ++cnt;
}
ASCII-to-Integer needs to convert data back from an ASCII represented string into an integer type.
All operations need to be performed using pointer arithmetic, not array indexing
The character string to convert is passed in as a uint8_t * pointer (ptr).
The number of digits in your character set is passed in as a uint8_t integer (digits).
You should be able to support bases 2 to 16.
The converted 32-bit signed integer should be returned.
This function needs to handle signed data.
You may not use any string functions or libraries.
.
int32_t my_atoi(uint8_t *ptr, uint8_t digits, uint32_t base){
int32_t sgnd=0, rslt=0;
for(int i=0; i<digits; i++){
if(*(ptr)=='-'){*ptr='0';sgnd=1;}
else if(*(ptr+i)>'9'){rslt+=(*(ptr+i)-'7');}
else{rslt+=(*(ptr+i)-'0');}
if(!*(ptr+i+1)){break;}
rslt*=base;
}
if(sgnd){rslt=-rslt;}
return rslt;
}
I don't know about good, but this is my implementation that I did while learning C
static int ft_getintlen(int value)
{
int l;
int neg;
l = 1;
neg = 1;
if (value < 0)
{
value *= -1;
neg = -1;
}
while (value > 9)
{
l++;
value /= 10;
}
if (neg == -1)
{
return (l + 1);
}
return (l);
}
static int ft_isneg(int n)
{
if (n < 0)
return (-1);
return (1);
}
static char *ft_strcpy(char *dest, const char *src)
{
unsigned int i;
i = 0;
while (src[i] != '\0')
{
dest[i] = src[i];
i++;
}
dest[i] = src[i];
return (dest);
}
char *ft_itoa(int n)
{
size_t len;
char *instr;
int neg;
neg = ft_isneg(n);
len = ft_getintlen(n);
instr = (char *)malloc((sizeof(char) * len) + 1);
if (n == -2147483648)
return (ft_strcpy(instr, "-2147483648"));
if (!instr)
return (NULL);
if (neg == -1)
n *= -1;
instr[len--] = 0;
if (n == 0)
instr[len--] = 48;
while (n)
{
instr[len--] = ((n % 10) + 48);
n /= 10;
}
if (neg == -1)
instr[len] = '-';
return (instr);
}
This should work:
#include <string.h>
#include <stdlib.h>
#include <math.h>
char * itoa_alloc(int x) {
int s = x<=0 ? 1 ? 0; // either space for a - or for a 0
size_t len = (size_t) ceil( log10( abs(x) ) );
char * str = malloc(len+s + 1);
sprintf(str, "%i", x);
return str;
}
If you don't want to have to use the math/floating point functions (and have to link in the math libraries) you should be able to find non-floating point versions of log10 by searching the Web and do:
size_t len = my_log10( abs(x) ) + 1;
That might give you 1 more byte than you needed, but you'd have enough.
There a couple of suggestions I might make. You can use a static buffer and strdup to avoid repeatedly allocating too much memory on subsequent calls. I would also add some error checking.
char *itoa(int i)
{
static char buffer[12];
if (snprintf(buffer, sizeof(buffer), "%d", i) < 0)
return NULL;
return strdup(buffer);
}
If this will be called in a multithreaded environment, remove "static" from the buffer declaration.
This is chux's code without safety checks and the ifs. Try it online:
char* itostr(char * const dest, size_t const sz, int a, int const base) {
bool posa = a >= 0;
char buffer[sizeof a * CHAR_BIT + 1];
static const char digits[36] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char* p = &buffer[sizeof buffer - 1];
do {
*(p--) = digits[abs(a % base)];
a /= base;
} while (a);
*p = '-';
p += posa;
size_t s = &buffer[sizeof(buffer)] - p;
memcpy(dest, p, s);
dest[s] = '\0';
return dest;
}
main()
{
int i=1234;
char stmp[10];
#if _MSC_VER
puts(_itoa(i,stmp,10));
#else
puts((sprintf(stmp,"%d",i),stmp));
#endif
return 0;
}

Resources