www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/02/25/06:00:28

From: Vik Heyndrickx <Vik DOT Heyndrickx AT rug DOT ac DOT be>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: !!Absolute value with inline ASM!!
Date: Wed, 25 Feb 1998 10:59:40 +0100
Organization: University of Ghent, Belgium
Lines: 50
Message-ID: <34F3EB8C.7623@rug.ac.be>
References: <D1FB30BBA491D1118E6D006097BCAE390B9202 AT Probe-nt-2a DOT Probe DOT co DOT uk> <6cch0m$khn$1 AT rosenews DOT rose DOT hp DOT com>
NNTP-Posting-Host: eduserv1.rug.ac.be
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Andrew Crabtree wrote:
> 
> Shawn Hargreaves wrote in message ...
> >Henri Ossi writes:
> >> I need to get the absolute value of a registers (bx)
> >> How is this done in asm.
> >> (in one command, not using cmp)
> >I don't know of any such method.
> Me neither.  Unless Intel has an undocumented abs instruction.

Nope. euh..., well, euh..., not AFAIK (and I claim to know a lot about
the instruction set }:-) IM(H)O)

> > I think a test followed by conditional
> >negation is probably the best you can do: that is what gcc produces for
> >the abs() function.
> 
> I can do better (well ok, some guy on comp.lang.asm.x86 did ;).  Eliminating
> the conditional is easy.  Just sign extend the value to the
> next size up (convert word to dword say), then xor the values, then
> subtract.  If the sign bit
> was zero then both the xor and sub are effectively nops.  If it was one then
> you negate everything,
> and then add 1 to it, which gives the exact 2s complement.

In an attempt to rewrite this understandable and usable:

inline unsigned absval (int a)
{
  unsigned retval;

  asm ("cdq\n\t"            // sign extend value in eax to edx (edx is
-1 or 0)
       "xorl %%edx,%0\n\t"  // effectively a NOT or a NOP
       "subl %%edx,%0"      // effectively an INC or a NOP
       : "=a" (retval)
       : "0" (a)
       : "dx");
  return retval;
}

Hope this works (I haven't tested it, but it has worked the previous
time I re-invented this)

BTW was I that guy in comp.lang.asm.x86? :-)

-- 
 \ Vik /-_-_-_-_-_-_/   
  \___/ Heyndrickx /          
   \ /-_-_-_-_-_-_/

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019