tags:

views:

143

answers:

5

In the C language: How do I convert unsigned long value to a string (char *) and keep my source code portable or just recompile it to work on other platform (without rewrite code)

For example with sprintf(buffer, format, value): how to determine the size of buffer with platform-independent manner

+1  A: 
char buffer [50];

unsigned long a = 5;

int n=sprintf (buffer, "%lu", a);
Jeffrey Vandenborne
A: 

Try using sprintf:

unsigned long x=1000000;
char buffer[21];
sprintf(buffer,"%lu", x);

Edit:

Notice that you have to allocate a buffer in advance, and have no idea how long the numbers will actually be when you do so. I'm assuming 32bit longs, which can produce numbers as big as 10 digits.

See Carl Smotricz's answer for a better explanation of the issues involved.

MAK
A: 

For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,

as a reference of available options see sprintf

#include <stdio.h>

    int main ()
    {
      unsigned long lval = 123;
      char buffer [50];
      sprintf (buffer, "%lu" , lval );
     }
stacker
+3  A: 
const int n = snprintf(NULL, 0, "%lu", ulong_value);
assert(n > 0);
char buf[n+1];
int c = snprintf(buf, n+1, "%lu", ulong_value);
assert(buf[n] == '\0');
assert(c == n);
J.F. Sebastian
Wonderful !!!This is what I'm searching for. Thank you
Walidix
Note the VLA (`char buf[n+1];`) requires C99.
KennyTM
@KennyTM: 2010.
J.F. Sebastian
+2  A: 

The standard approach is to use sprintf(buffer, "%lu", value); to write a string rep of value to buffer. However, overflow is a potential problem, as sprintf will happily (and unknowingly) write over the end of your buffer.

This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.

This site discusses this and related problems at some length.

Some libraries offer snprintf as an alternative which lets you specify a maximum buffer size.

Carl Smotricz
Yes, i would use `snprintf`. It's Standard, and it provides support for completely solving this.
Johannes Schaub - litb
Contradicting your gravatar, +1 for sanity.
Tim Post
Printing a number is a case where you don't need `snprintf`; you can easily bound the size of buffer required. (Printing with `%s` OTOH, that requires caution.)
Donal Fellows
Many programmers will feel better specifying a very explicit upper bound with `snprintf` than using considerations about the sizes of numbers to mathematically establish such a bound or -worse, IMO- fiddling with logarithms to pre-calculate that size.
Carl Smotricz