Re: Trick with SBB instruction
From: Terje Mathisen (spamtrap_at_crayne.org)
Date: Mon, 10 Jan 2005 22:52:09 +0000 (UTC)
> I have seen some (uncommented) Intel assembler code that
> frequently uses the following pair of lines:
> sbb eax,eax
> sbb eax,0FFFFFFFFh
> and I was wondering what this is intended to achieve.
> Some Googling on 'sbb' indicates that the first is a
> well-known trick for setting eax to 0 if the carry flag
> is not set and to 0FFFFFFFFh otherwise.
Right, SBB is used to replicating the carry flag across the entire
register. As a side-effect, it will also maintain the incoming carry flag.
This means that the second SBB will either subtract -1 from zero, i.e.
adding 1 to generate 1, or subtract (-1 + 1) = 0 from -1.
I.e. the idiom seems to turn a carry flag into either +1 or -1, which
would be perfect for a signum function.
-- - <Terje.Mathisen@hda.hydro.com> "almost all programming can be viewed as an exercise in caching"