Let Go, Standard Library From Community

Dan murpsoft at hotmail.com
Wed Apr 18 14:02:19 PDT 2007


Frits van Bommel Wrote:

> Dan wrote:
> > 
> > Oh my...
> > 
> > I went through tango.core.Array and tango.math.Math and personally found several rather junior mistakes like:
> > 
> > int abs(int x){
> >   return x > 0? x : -x;
> >  // should be: return x &= 0x7FFF_FFFF;
> > }
> 
> ...
> 
> That's *so* wrong...
> You may want to save yourself some embarrassment by checking code before 
> you post it here:

Bah... you know what I meant.  Unpredicted branches on an x86 cost roughly 6 cycles, not including the neg; we assume for both cases that we're inlining the function (no call overhead)

What I intended to show was that you could do it better with a touch of bit math.

I think the right way is actually to use something like asm's:

rol EAX, 1; // 1000_0001 becomes 0000_0011
shr EAX, 1; // 0000_0011 becomes 0000_0001

Of course, I can't test this.  I'm at work, not at home with my development box. I may have also used the wrong right shift instruction, or used the rotate that goes through the sign bit in EFLAGS.

Surely one of the asm gurus has presented this already?

So I looked around a bit.

Some further reading:
http://www.azillionmonkeys.com/qed/2scomp.html
http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs




More information about the Digitalmars-d mailing list