Re: Is this a guaranteed signed/unsigned conversion?
- From: Christian Bau <christian.bau@xxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 21 May 2005 00:57:33 +0100
In article <428E4387.2AB6D720@xxxxxxxxx>,
CBFalconer <cbfalconer@xxxxxxxxx> wrote:
> Consider:
>
> #include <stdlib.h>
>
> /* An elementary optimizer is expected to remove most code */
> /* Return the absolute value */
> unsigned long ulabs(long j)
> {
> if (0 == LONG_MIN + LONG_MAX) {
> if (j < 0) return -j;
> else return j;
> }
> else if (LONG_MIN == j) return 1U + j + ULONG_MAX;
> else if (j < 0) return -j;
> else return j;
> } /* ulabs */
>
> Is this guaranteed to convert all long values to their absolute
> unsigned long equivalent, assuming that the desired result is
> representable as an unsigned long. Does it work over 2's, 1's
> complement and sign-magnitude? Is there a better method? labs()
> is not guaranteed.
I think it will work; I believe it is guaranteed that LONG_MIN +
LONG_MAX is either 0 or -1.
What about this:
unsigned long ulabs (long j) {
return j >= 0 ? (unsigned long) j : 0ul - j;
}
I think this should work. The case j >= 0 is obviously fine. If j < 0,
then evaluating (0ul - j) will convert j to unsigned long; since the
value of j cannot be represented ULONG_MAX + 1 will be added as often as
needed (that is once) giving (j + ULONG_MAX + 1). The subtract operation
gives - (j + ULONG_MAX + 1) and since the result is negative, ULONG_MAX
+ 1 is again added as often as necessary (that is once), giving -j.
.
- References:
- Is this a guaranteed signed/unsigned conversion?
- From: CBFalconer
- Is this a guaranteed signed/unsigned conversion?
- Prev by Date: Re: WAV file question
- Next by Date: Re: useful tips on how to write your C codes more efficiently
- Previous by thread: Re: Is this a guaranteed signed/unsigned conversion?
- Next by thread: Re: Is this a guaranteed signed/unsigned conversion?
- Index(es):
Relevant Pages
|