bug-grep
[Top][All Lists]

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

 From: Stepan Kasal Subject: [bug-grep] Re: length of dec. representation of a number Date: Mon, 7 Mar 2005 15:05:18 +0100 User-agent: Mutt/1.4.1i

```Hi,

On Sat, Mar 05, 2005 at 09:04:17AM -0800, Paul Eggert wrote:
> > 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.

I vote for 146/485.  I see no problem.
The fact that it can be used with 16-bit ints can help someone, and they can
grab the code and paste it somewhere else.

You cannot verify that "log10(2) is approx 0.301029996" without a calculator
(eg. bc), and as soon as you have it, there is no problem checking that
"146 / 485 is log10 (2) rounded up".

And I think we can happily use the old trick "add one instead of rounding
up".  When can the division have no reminder?   In other words, when can
the expression
(sizeof (t) * CHAR_BIT - TYPE_SIGNED (t)) * 146
be a multiple of 485?
A quick check says that with CHAR_BIT == 8, the smallest size where we can
have problems is 182 bytes.  So, if we had 182-byte signed integer, we
would allocate 441 bytes instead of the minimum of 440 bytes (including
the final '\0').
I think we can live with that.

So below is the alternative which would I prefer.

/* 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;
146 / 485 is log10 (2) rounded up;
add one for a minus sign if t is signed.  */
#define INT_STRLEN_BOUND(t) \
((sizeof (t) * CHAR_BIT - TYPE_SIGNED (t)) * 146 / 485 + 1 + TYPE_SIGNED (t))

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

Stepan

```