Re: Is this a guaranteed signed/unsigned conversion?



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.
.



Relevant Pages

  • Re: Potential Transformer
    ... sample the waveforms of each. ... replace the current older wattmeters used in our labs. ... Prev by Date: ...
    (sci.electronics.design)
  • Re: How to hide duplicate records but show them once
    ... sort the column that has the values you are evaluating. ... barrfly's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=4141 ... Prev by Date: ...
    (microsoft.public.excel.misc)
  • Re: Veni,vidi, but no vici.
    ... | Next labs in January. ... | before doing the majority of the tests. ... and you don't need meds for it. ... Prev by Date: ...
    (alt.support.diabetes)
  • Re: Man killed in London not connected to blasts
    ... Robert Low writes ... Then again I suppose you could quickly start evaluating pi - give ... of the IRA ... Prev by Date: ...
    (rec.martial-arts)
  • Re: "Risk factor"
    ... looked at it and wrote the prescriptions and the labs. ... I try to massage them but I no longer bend over for them. ... Prev by Date: ...
    (alt.support.diabetes)