liveBook · Manning

Integer wraparound

As explained in Systems Programming with Zig

Wrapping arithmetic is integer arithmetic whose result wraps modulo the destination type's representable range on overflow.

Wrapping arithmetic lets CHIP-8 instructions add or subtract values even when the result overflows. In Zig, +% makes wrapping addition explicit; -% and *% provide wrapping subtraction and multiplication. For overflow-aware arithmetic, @addWithOverflow and @subWithOverflow return the wrapped result and an overflow bit. section 6.5.4

Table 6.3 More register instructions
Mnemonic Description

7XKK

Add a constant to a register, wrapping on overflow.

8XY0

Set register X to the value of register Y.

8XY1

Set register X to X | Y.

8XY2

Set register X to X & Y.

8XY3

Set register X to X ^ Y.

8XY4

Set register X to X + Y, and register 0 to the value of the overflow bit.

8XY5

Set register X to X - Y, and register 0 to a 1 if the result is negative (subtraction overflow for unsigned values is equivalent to producing a negative number).

See wrapping register addition in opcode 7XKK, alongside other register instructions. section 6.5.4

How Systems Programming with Zig covers it

How deep it goes
Defines wrapping operators, contrasts ordinary addition's debug-mode panic, and describes overflow-reporting builtins.
Examples
Uses opcode 7XKK for wrapping register addition and BMMM and FX1E for wrapping address additions.
What you can do after
Apply Zig's wrapping operators to implement CHIP-8 arithmetic that wraps on overflow.
How it connects
Ties wrapping operators to CHIP-8 register arithmetic, program-counter updates, and overflow detection.

Also explained in

Compare how 4 books explain integer wraparound →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Systems Programming with Zig. The section links point to the parts of the book it draws on.