remu

remu

RISC-V Assembly Reference

lyszt.net covers remu and other RISC-V instructions in more detail.

Encoding format

R
31–25funct7
24–20rs2
19–15rs1
14–12funct3
11–7rd
6–0opcode
I
31–20imm[11:0]
19–15rs1
14–12funct3
11–7rd
6–0opcode
S
31–25imm[11:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:0]
6–0opcode
B
31–25imm[12,10:5]
24–20rs2
19–15rs1
14–12funct3
11–7imm[4:1,11]
6–0opcode
U
31–12imm[31:12]
11–7rd
6–0opcode
J
31–12imm[20,10:1,11,19:12]
11–7rd
6–0opcode

Description

remu computes the unsigned remainder, the value left over after an unsigned division. It relates to divu as rem relates to div. The u means the bits are treated as non-negative numbers, from 0 up to roughly 4 billion. The divu page covers how signed and unsigned readings of the same bits differ.

A remu result always falls between 0 and the divisor minus 1, so it is never negative and has no sign rule. This makes it useful for wrapping a position around a circular buffer, distributing hash values over a fixed number of slots, and cycling through a repeating sequence.

A remainder by zero returns the original number.

According to the RISC-V manual, unsigned division overflow cannot occur, so remu has no overflow case. A remainder by zero equals the dividend. The manual recommends running divu and remu on the same operands when both the quotient and the remainder are needed, so a processor can fuse them into one division.

For a divisor that is a power of two, a bitwise AND (andi) yields the same result more cheaply. The line below computes the remainder after dividing by 8, since the remainder by a power of two is the lowest bits of the value.

andi t0, t0, 7

This shortcut applies only to powers of two.

Example

li t0, -1
li t1, 10
remu t2, t0, t1   # t2 = 5 (t0 read as unsigned)