Well you could always do y = x&(1<<31); y |= (y>>1)|(y>>2)|...|(y>>31); // all this just to avoid an if which probably costs nothing while the processor does both possibilities in parallel ? (And of course this all assume 32-bit integers.) But the original question wasn't about C, it was about "your computer". [jpg was presumably just using C notation for exposition.] And of course, then it depends on what the instruction set has in it, which wasn't specified. Also what wasn't specfied was whether x was fixed or floating point, or even what number formats the processor natively uses. If the format is sign/magnitude (which I believe the IEEE binary floating point standard is), the problem gets easier. By the way, if you want to have overflow detected, then instead of x^y - y, use x*(y*2+1). --ms On 24-Aug-13 02:31, Joerg Arndt wrote:
* J.P. Grossman <jpg@alum.mit.edu> [Aug 24. 2013 08:11]:
Assuming x is a 32-bit integer, here's one way that uses 3 instructions:
int y = x >> 31; Here you assume that the sign bit gets spread out. IIRC the C standard does not guarantee this ("arithmetic right shift").
Cf. fxtbook, section "1.11 Avoiding branches" p.25ff for a selection of such tricks. The section contains one bad error that has not been documented in the errata. Where is it?
Best, jj
int negx = (x ^ y) - y;
J.P.
On Fri, Aug 23, 2013 at 4:25 PM, Warren D Smith <warren.wds@gmail.com>wrote:
suppose my computer wants |x| but it refuses to perform an "if" statement.
What to do?
[...]
math-fun mailing list math-fun@mailman.xmission.com http://mailman.xmission.com/cgi-bin/mailman/listinfo/math-fun