How to round to an integer without branching in Assembly?

6.3k Views Asked by At

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?

5

There are 5 best solutions below

4
Tommy On BEST ANSWER

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

3
Alan On

An integer doesn't have decimal places, therefore it is already a whole number.

0
corsiKa On

Assuming you were given only integers, and just told that one of the integers needs to be treated like a decimal using a scale factor... then you can do this by going using a scale factor that is twice as large as you need. So instead of 100, you use 200. This will cause the last bit of the result to be 1 or 0 depending on whether or not you will round up.

So in c style it looks like this

result = (195 * 85) / (100 / 2);
add = result & 1;
result = result / 2 + add;

If you weren't supposed to round up (i.e. round down) then the 'add bit' will be 0. Otherwise the 'add bit' will be 1 if you're supposed to round up.

I think that should give you the pseudocode you need to translate this into assembly properly.

0
Munchy G On

In x86 assembly, there's the FRNDINT instruction.

2
Ddystopia On

For positive and negative numbers, 6 strings in asm.

double round(double x) {
  return (long)(x + 0.5 + (*(long*)&x >> 63));
}