Integer overflow: Difference between revisions

Content added Content deleted
m (→‎{{header|6502 Assembly}}: Correction: OR does not set the overflow on 6502)
m (→‎{{header|6502 Assembly}}: added section on 16 bit overflow)
Line 132: Line 132:
BITFPO DC BL1'00001000' bit20=1 [start at 16]</lang>
BITFPO DC BL1'00001000' bit20=1 [start at 16]</lang>
=={{header|6502 Assembly}}==
=={{header|6502 Assembly}}==
===8-Bit Overflow===
Signed overflow (crossing the 7F-80 boundary) is detected by the CPU's overflow flag <code>V</code>
Signed overflow (crossing the 7F-80 boundary) is detected by the CPU's overflow flag <code>V</code>
Unsigned overflow from 255 to 0 is detected by the CPU's carry flag <code>C</code>.
Unsigned overflow from 255 to 0 is detected by the CPU's carry flag <code>C</code>.
Line 171: Line 172:


By default, the CPU will continue with the wrong result, unless you specifically program a branch based on overflow after the calculation. This is because on a hardware level the CPU has no knowledge of whether you intend your data to be signed or unsigned (this is still true even on modern computers).
By default, the CPU will continue with the wrong result, unless you specifically program a branch based on overflow after the calculation. This is because on a hardware level the CPU has no knowledge of whether you intend your data to be signed or unsigned (this is still true even on modern computers).

===16-Bit or Higher Overflow===
Unlike in [[Z80 Assembly]], the 6502 has no 16-bit registers or built-in 16-bit arithmetic instructions. It ''can'' perform 16-bit or higher addition and subtraction, by separating the number into 8-bit pieces and operating on them separately. Unfortunately, this means that the 6502's flags cannot look at the number as a whole; only the individual bytes. As a result, the CPU will detect "overflow" when any of the bytes cross the $7F-$80 boundary, regardless of whether the byte is the most significant byte or not. This is another reason why the ability to selectively ignore overflow is handy, as it only counts as signed overflow when the most significant byte crosses the $7F-$80 boundary.

<lang 6502asm>;adding two 16-bit signed numbers, the first is stored at $10 and $11, the second at $12 and $13.
;The result will be stored at $14 and $15.

;add the low bytes

LDA $10 ;low byte of first operand
CLC
ADC $12 ;low byte of second operand
STA $14 ;low byte of sum

;add the high bytes

LDA $11 ;high byte of first operand
ADC $13 ;high byte of second operand
STA $15 ;high byte of result
BVS HandleOverflow ;only check for overflow when adding the most significant bytes.</lang>


=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==