assemblyroundingbranchless

How to round to an integer without branching in Assembly?


How do I round a real number to the nearest integer in Assembly? The use of branching is not allowed here.

For example, 195 * .85 = 165.75. Normally, I'd multiply 195 by a scale factor (100) and then multiply, then divide down the scale factor. This would give me 165. How do I get 166?


Solution

  • For example, 195 * .85 = 165.75. Normally, I'd multiply 195 by a scale factor (100) and then multiply, then divide down the scale factor. This would give me 165. How do I get 166?

    Classically you'd use a power of two scale factor and shift rather than multiply and divide; I guess now that divides and multiplies cost the same as shifts on many architectures you may be more concerned with keeping a certain precision.

    Anyway, as almost suggested by halex, you'd add 0.5 before dividing. The net effect will be that if the decimal part is already 0.5 or greater you'll get carry into the integer part. If not then there'll be no carry.

    So:

    195 * 100 = 19500
    19500 * 0.85 = 16575
    16575 + 50 (ie, 0.5) = 16625
    16625 / 100 = 166