bug-gnulib
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[bug-gnulib] Re: [bug-grep] length of dec. representation of a number


From: Paul Eggert
Subject: [bug-gnulib] Re: [bug-grep] length of dec. representation of a number
Date: Sat, 05 Mar 2005 09:04:17 -0800
User-agent: Gnus/5.1006 (Gnus v5.10.6) Emacs/21.4 (gnu/linux)

address@hidden (Paul Jarc) writes:

> Just for fun, I calculated an optimal fraction.  146/485 is the
> smallest overestimate of log10(2) that can be used to calculate
> (without overflowing a 16-bit signed int) the number of bytes needed

GNU code can assume 32-bit int, so it's less obscure to use 30103 / 100000.
log10(2) is about 0.301029996, so that's pretty close.

Here's what I've drafted so far -- I haven't tested it though.  I'm
planning to turn this sort of thing into a separate gnulib module with
an include file named "int-props.h" or something like that; this sort
of code is used in several places in gnulib and coreutils now, and
should be factored out.

/* The extra cast works around compiler bugs.  */
#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))

/* Bound on length of the string representing an integer value of type t.
   Subtract one for the sign bit if t is signed;
   30103 / 100000 is log10 (2) rounded up;
   round the result up;
   add one for a minus sign if t is signed.  */
#define INT_STRLEN_BOUND(t) \
 (((sizeof (t) * CHAR_BIT - TYPE_SIGNED (t)) * 30103 + 99999) / 100000 \
  + TYPE_SIGNED (t))

#define INT_BUFSIZE_BOUND(t) (INT_STRLEN_BOUND (t) + 1)




reply via email to

[Prev in Thread] Current Thread [Next in Thread]