If no overflow means the arithmetic result is representable as an 8-bit signed value, then the following rules should apply:
- if
y = 0
, then no overflow.
- if
y > 0
, then overflow if truncate(x - y) > x
.
- if
y < 0
, then overflow if truncate(x - y) < x
.
Here truncate(x)
means the truncated 8-bit signed value of x
.
Then the code may look like this:
lda y ; Load y.
mov b, a
lda x ; Load x.
mov c, a
sub b ; No overflow if truncate(x - y) = x, that is, y = 0.
cmp c
jz no_overflow
jm else ; Jump if truncate(x - y) < x.
; At this point y != 0 and truncate(x - y) > x.
mov a, b ; Overflow if y > 0.
ana a
jp overflow
no_overflow:
...
; At this point y != 0 and truncate(x - y) < x.
else:
mov a, b ; Overflow if y < 0.
ana a
jp no_overflow
overflow:
...
As an optimization measure, the two mov a, b
instructions can be replaced with a single mov a, b
just before jm else
.