How to round to an integer without branching in assembly?

安稳与你 提交于 2021-02-10 03:07:06

问题


How do I round an integer to the nearest whole 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?

I'm sorry if this is a terrible question - I'm new to assembly! Thank you.


回答1:


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




回答2:


In x86 assembly, there's the FRNDINT instruction.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/12828166/how-to-round-to-an-integer-without-branching-in-assembly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!