Re: C function for returning number of digits?




Niklas Norrthon schrieb:

> "Ingo Menger" <quetzalcotl@xxxxxxxxxxxxxx> writes:
>
> > Richard Bos schrieb:
> >
> > > Keith Thompson <kst-u@xxxxxxx> wrote:
> > >
> > > > "Luke Wu" <LookSkywalker@xxxxxxxxx> writes:
> > > > > Ohh my.... didn't think it would be a two liner.......thank you
> > > > > #include<math.h>
> > > > >
> > > > > int numdigits(int n)
> > > > > return log10(n) + 1;
> > > >
> > > > I don't think a floating-point solution is best here. A loop using
> > > > integer arithmetic is likely to be faster and more accurate. For that
> > > > matter, a binary search on a lookup table holding powers of 10 is
> > > > likely to be even quicker.
> > >
> > > *g* Never knock the simple solution. You're quite right, of course
> >
> > How about:
> > int length;
> > char digits[100]; /* should be big enough even for 128 bit longs */
> > sprintf(digits, "%d", n);
> > length = strlen(digits) - (n<0 ? 1 : 0);
>
> And how do you fix this when the next version of your compiler ships
> (which use 333 bit longs)?

I don't. I write the length of the char array as constant expression
involving sizeof (long) in the first place. For example
char digits[32 + 4 * sizeof (long)]
That should do it.

.