Question

gcc 4.7.2
c89
APR 1.4

Hello,

I am compiling my program in 32 bit mode i.e. -m32 as some of the libraries I am linking with use 32 bit libraries.

I have the following structure:

struct tag_channel {
    apr_int32_t id;
    char *name;
};

For the id I want to have a random number so I am using the APR:

apr_time_t time_secs = apr_time_sec(apr_time_now());

I am wondering about casting because apr_time_sec returns an apr_time_t type which is:

typedef apr_int64_t

I could cast into the following:

channel->id = (apr_int32_t)time_secs;

However, I am worried about the loss of value by casting down.

The following is 64bit, so not sure if this would work.

#define APR_TIME_T_FMT   APR_INT64_T_FMT

I don't want to change the channel structure for the id to apr_time_t as it doesn't really make sense to have time value for an ID value.

Which is the best way to cast this?

Many thanks for any suggestions,

Était-ce utile?

La solution

Consider using apr_time_usec for desired random number. apr_time_usec seems to be "more random", because it returns usecond part (the whole time is sec + APR_USEC_PER_SEC * usec) and is guaranteed to be inside [0 .. 1000000] by definition, so you may don't worry about loosing precision with cast.

If using seconds, not useconds is crucial, then you may calculate your random number as

channel->id = (apr_int32_t) (apr_time_sec(apr_time_now()) % INT32_MAX)

(don't forget to include limits.h) to fit it inside 32-bit diapason some smarter then just by truncation.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top