实际如何计算模运算符(%)? [英] How is the modulo operator (%) actually computed?

查看:289
本文介绍了实际如何计算模运算符(%)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我对模运算符%感到困惑.

Recently I've been confused about the modulo operator, %.

已知a % b == a-a/b*b当我们有整数ab其中a > b时,如果ab足够小,我们可以手动进行此计算.

It's known that a % b == a-a/b*b when we have integers a and b where a > b, and we can do this calculation by hand if a and b are small enough.

但是,当涉及到处理器的计算方式时,处理器是否使用与前面提到的相同的方法a-a/b*b?也许只是通过将除法运算转换为减法或加法运算,或者可能涉及某些转换?

However, when it comes to the way a processor computes it, does the processor use the same method as previously mentioned, a-a/b*b? Maybe just by translating the division into subtraction or addition, or is there some shifting involved perhaps?

推荐答案

除2的幂以外,模运算符可以(并且在大多数优化的编译器中)可以转换为简单的按位运算,恐怕唯一的做到这一点的方法是困难的.说明是 http://en.wikipedia.org/wiki/Modulooperation

Except for powers of 2, where the modulo operator can (and in most optimizing compilers is) be turned into a simple bitwise operation, I'm afraid the only way to do it is the hard way. Explanation is http://en.wikipedia.org/wiki/Modulo_operation

在另一个答案中,@ Henk Holterman指出某些CPU在微代码中执行此操作,而其余部分在进行整数除法时保留在寄存器中,这意味着模指令可以减少为整数除法并返回余数. (我在此处添加该信息,因为此答案已被接受.)

In another answer, @Henk Holterman points out that some CPUs do it in the microcode, leaving the remainder in a register while doing an integer divide, which means the modulo instruction can be reduced to an integer divide and return the remainder. (I'm adding that information here because this answer has already been accepted.)

这篇关于实际如何计算模运算符(%)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆