bug-grep
[Top][All Lists]
Advanced

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

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

 From: Stepan Kasal Subject: Re: length of dec. representation of a number [bug-grep] [bug-gnulib] Date: Thu, 10 Mar 2005 13:53:37 +0100 User-agent: Mutt/1.4.1i

```On Thu, Mar 10, 2005 at 09:53:22AM +0100, Jim Meyering wrote:
> address@hidden (Paul Jarc) wrote:
> > #define INT_STRLEN_BOUND(t) \
> >   ((sizeof (t) * CHAR_BIT - TYPE_SIGNED(t)) * 146 / 485 + TYPE_SIGNED(t) +
> > 1)

> Technically, yes, but that would prohibit applying that macro
> to variables, which is useful.  Currently there are uses like
> that in the coreutils.

OK, I thanks for explanation.  Anyway, I vote for documenting this here:

/* Bound on length of the string representing an integer value or type T.
Subtract 1 for the sign bit if t is signed; log10 (2.0) < 146/485;
add 1 for integer division truncation; add 1 more for a minus sign
if needed.  Thus the bound should be
(sizeof (t) * CHAR_BIT - TYPE_SIGNED(t)) * 146 / 485 +
TYPE_SIGNED(t) + 1
But TYPE_SIGNED cannot be used when `t' is a variable, so we avoid
using it.  The bound for signed type is slightly bigger than for the
corresponding unsigned one, so we can use the following estimate:  */
#define INT_STRLEN_BOUND(t) \
((sizeof (t) * CHAR_BIT - 1) * 146 / 485 + 2)

/* How much do we lose for unsigned type?  At most one byte, of course.
Looking at the most common cases, we see that for unsigned integers
which are 64, 256, 512, 1024 bits wide, this expression gives the
right size.  For 16 and 32 bits, INT_BUFSIZE_BOUND doesn't cross
any 4-byte multiple.  Only with 128-bit unsigned integer, the estimate
reported by INT_BUFSIZE_BOUND changes from 40 bytes to 41 bytes.
The most common usage is to allocate INT_BUFSIZE_BOUND(t) bytes for
a string.  In that case the 128-bit integer in combination with
allocator which could give us exactly 40 bytes is the only case where
we loose anything.  */

Well, this second comment is probably going into details and shouldn't
go to the header.  Anyone interested can re-compute their own case.

But I suggest that you place the first comment above the macro, so that
anyone sees the reasons for the decisions taken.

Have a nice day,
Stepan

```

reply via email to

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