sltu
lyszt.net covers sltu and other RISC-V instructions in more detail.
Encoding format
Description
sltu sets the destination register to 1 or 0 like slt, and it compares two numbers as unsigned values. The name stands for set less than, unsigned. The slt page covers storing a comparison result as a 1 or a 0.
The same 32 bits can be read as a signed number, with the top bit meaning negative and a range of roughly -2 billion to +2 billion, or as an unsigned number, with no negatives and a range of 0 to about 4 billion. slt reads the signed value and sltu reads the unsigned one. A register with all bits set to 1 is -1 to slt and the largest possible value to sltu, so the two instructions can disagree on identical inputs.
Use sltu for quantities that cannot be negative, such as memory addresses, sizes, counts and positions. Comparing two memory addresses with the signed slt gives a wrong result once an address is large enough to set its top bit, since the signed reading treats it as negative.
The RISC-V manual describes slt and sltu together as the signed and unsigned compares that write 1 to rd if rs1 is less than rs2 and 0 otherwise. It gives the line below as the way to test for non-zero, which is the snez pseudo-instruction.
sltu rd, x0, rs2
The form of sltu is shown below.
sltu rd, rs1, rs2
In the special case below, rd becomes 1 whenever rs is anything other than zero, since 0 is less than every other unsigned value. This reduces any number to a 1 or a 0.
sltu rd, zero, rs
Example
li t0, -1 li t1, 1 sltu t2, t0, t1 # t2 = 0 (t0 read as unsigned is huge)
