divu

divu

RISC-V Assembly Reference

lyszt.net covers divu 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

divu performs unsigned division. A register's 32 bits can be interpreted in two ways. Under the signed reading, the top bit signals a negative number, so the bits represent values from about -2 billion to +2 billion. Under the unsigned reading, no negatives exist and the bits count from 0 to about 4 billion. The bits do not change. Only the interpretation does.

div treats its inputs as signed, while divu treats them as unsigned. Near the top of the range the two produce different results. A register with all bits set to 1 is -1 to div and 4,294,967,295 to divu.

divu suits values that cannot be negative: array positions, sizes in bytes, loop counts, pixel coordinates. Once one of these values passes about 2 billion, signed div returns wrong results. The top bit turns on, and the signed reading makes the value negative.

The RISC-V manual defines the quotient of an unsigned division by zero as all bits set, and the remainder as equal to the dividend. Unsigned division overflow cannot occur, according to the manual. All bits set is the largest unsigned number, and simple unsigned divider circuits produce it on their own. That is why the manual chose it.

Division by zero returns the largest unsigned value, with all bits set. If the divisor is a power of two, a logical right shift (srli) divides faster. Shifting right by 3 divides an unsigned number by 8.

Example

li t0, -2
li t1, 2
divu t2, t0, t1   # t2 = 2147483647 (t0 read as unsigned)