Hacker News new | ask | show | jobs
by omoikane 27 days ago
See also:

https://en.wikipedia.org/wiki/Saturation_arithmetic

1 comments

From the Wikipedia article:

> However, it is possible to implement saturating addition and subtraction in software without branches, using only modular arithmetic and bitwise logical operations that are available on all modern CPUs and their predecessors, including all x86 CPUs (back to the original Intel 8086) and some popular 8-bit CPUs (some of which implement the Z80 instruction set) are still in production.

Does anyone know what the implementation of this is, without conditional moves?

Here is one in plain 68000 assembler.

  move.b #200,d0
  move.b #100,d1
  add.b  d0,d1   ; 8th bit goes to X flag
  subx.b d0,d0   ; d0 = $00 or $ff depending on X flag
  or.b   d0,d1   ; d1 = 255 if there was saturation
You can do the same with all others that somehow store the 8th bit carry somewhere then allow using it for substraction.