Signed power-of-two division by biasing
ID: signed-power-of-two-division-by-biasing
For signed two's complement integers, a conditional positive bias converts the rounding behaviour of an arithmetic right shift into C integer division. It can be formed without a conditional branch by turning the sign bit into either zero or a low--bit bit mask.
Proof. Nonnegative needs no adjustment. If , write , . Then , whose quotient rounded down is , exactly the quotient truncated towards zero. The bias fits safely for in an -bit signed word: it is added only to negative inputs, and the largest possible adjusted input is . The corresponding remainder is , where .
New to topics? Read the docs here!