I came across this snippet in a book about Computer Organization
Treating signed numbers as if they were unsigned gives us a low cost way of checking if 0 ≤ x < y, which matches the index out-of-bounds check for arrays. The key is that negative integers in two's complement notation look like large numbers in unsigned notation; that is, the most significant bit is a sign bit in the former notation but a large part of the number in the latter. Thus, an unsigned comparison of x < y also checks if x is negative as well as if x is less than y.
As an example of this, let's say we have registers $t0
, $t2
and $s1
want to jump to an instruction IndexOutOfBounds
if $s1 ≥ $t2
or if $s1
is negative.
This can be done using the MIPS instructions
sltu $t0,$s1,$t2
beq $t0,$zero,IndexOutOfBounds
Why does this work?