Fog Creek Software
Discussion Board




Matthew Wilson on integer to string conversion

I came across this series of articles after reading "checked atoi() or strtol() for C/C++". I'm not sure if there's anything that's perfect for the OP's needs, but it's a much more in-depth discussion of the issue than I could manage.

http://www.cuj.com/documents/cuj0212wilson/
http://www.cuj.com/documents/cujexp0309wilson/
http://www.cuj.com/documents/s=8906/cujexp0311wilson/

comp.lang.c refugee
Saturday, August 07, 2004

D'oh.

These articles, of course, discuss the opposite conversion.

comp.lang.c refugee
Saturday, August 07, 2004

I read through those articles with increasing incredulity that anyone, in this day and age (well, less than a year ago), was seriously suggesting the use of fixed-size buffers.  (Yes, they're long enough to hold 64-bit integers, how nice.  So what happens when Visual Studio 2010 defines "long long" as 128 bits?  Even if you detect that at compile time, how many programmers really want to waste time fixing bugs in basic library functions?!)

Not only that, but a *limited number* of them.  I'll put it this way - if I wrote a library that had a hardcoded limit of 32 concurrent conversions per thread, and failed *silently* if this assumption proved incorrect, I'd be out of a job.  And I'd deserve to be.

...
Saturday, August 07, 2004

I can imagine that there might be some applications where integer to string conversion happens so frequently that allocating memory each time is too big a performance hit. However, I can't think of any off the top of my head.

If I did encounter such a situation (having profiled and confirmed that memory allocation was the problem) I could see using a fixed-size buffer. However, I'd certainly include run-time checks to prevent overflow. I'd also have the buffer size be controlled by a build script which determines the number of digits in INT_MAX on the target platform.

For integer to string conversion I'd probably use boost::lexical_cast if programming in C++, because it's the most concise way I've found to do it. In C99, the next best is probably something like this:

#include <stdio.h>
#include <stdlib.h>

char *int2str(int n)
{
  size_t sz = 1 + snprintf(NULL, 0, "%d", n);
  char *s = malloc(sz);

  if (s)
    snprintf(s, sz, "%d", n);

  return s;
}

It gets messier if you don't have a C99-style snprintf handy.

comp.lang.c refugee
Saturday, August 07, 2004

The issue of buffer size is discussed extensively in the article, if you bother to read it.

Stan
Saturday, August 07, 2004

*  Recent Topics

*  Fog Creek Home