如何仅使用逻辑运算符AND判断数字是否为4的倍数? [英] How can I tell if a number is a multiple of four using only the logic operator AND?

查看:184
本文介绍了如何仅使用逻辑运算符AND判断数字是否为4的倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对汇编语言编程感到困惑,并且很好奇如何使用逻辑运算符AND判断数字是否为4的倍数?

I'm messing with assembly language programming and I'm curious how I could tell if a number is a multiple of 4 using the logic operator AND?

我知道如何使用"div"或"remainder"指令执行此操作,但是我正在尝试通过数字/单词的位操作来实现.

I know how to do it using "div" or "remainder" instructions but I'm trying to do this with bit manipulation of number/word.

有人能指出我正确的方向吗?我正在使用MIP,但与语言无关的答案很好.

Can anyone point me in the right direction? I'm using MIPs but a Language agnostic answer is fine.

推荐答案

好,要检测数字是否为另一个的倍数,只需执行x MOD y.如果结果为0,则它是偶数.

Well, to detect if a number is a multiple of another, you simply need to do x MOD y. If the result is 0, then it is an even multiple.

对于2的每个y(x MOD y)等同于(x AND (y - 1)).

因此:

IF (x AND 3) == 0 THEN
    /* multiple of 4 */

好的,您想知道为什么 (x MOD y) == (x AND (y - 1))y是2的幂时,我会尽力解释.

ok, you want to know why (x MOD y) == (x AND (y - 1)) when y is a power of 2. I'll do my best to explain.

基本上,如果一个数字是2的幂,则它具有一个单一的位置1(因为二进制是以2为底).这意味着所有低位均未置位.例如:16 == 10000b, 8 == 1000b

Basically, if a number is a power of 2, then it has a single bit set (since binary is base 2). This means that all of the lower bits are unset. So for example: 16 == 10000b, 8 == 1000b, etc.

如果从这些值中的任何一个减去1.最后,您将设置的位设置为未设置,而所有设置在其下方的位都将设置为

If you subtract 1 from any of these values. You end up with the bit that was set being unset and all bits below it being set.

15 = 01111b, 7 = 0111b等.因此基本上会创建一个掩码,该掩码可用于测试是否设置了任何低位.我希望这很清楚.

15 = 01111b, 7 = 0111b, etc. So basically it is creates a mask which can be used to test if the any of the lower bits were set. I hope that was clear.

BastienLéonard的评论也涵盖了这一点:

Bastien Léonard's comment covers it well too:

如果将(无符号)除以4,则表示 向右移动两位.就这样 剩下的就是那两个位 当你分裂时迷路了. 4-1 = 11b, 也就是说,产生两个面膜 当您将最右边的位与 值.

if you divide (unsigned) by 4, you shift two bits to the right. Thus the remainder is those two bits, which get lost when you divide. 4 - 1 = 11b, that is, a mask that yields the two rightmost bits when you AND it with a value.

编辑:请参阅此页面以获取更清晰的解释: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two .

see this page for possibly clearer explanations: http://en.wikipedia.org/wiki/Power_of_two#Fast_algorithm_to_check_if_a_positive_number_is_a_power_of_two.

它涵盖了检测2的幂,如果是2的幂,则使用AND作为快速模运算.

It covers detecting powers of 2 and using AND as a fast modulo operation if it is a power of 2.

这篇关于如何仅使用逻辑运算符AND判断数字是否为4的倍数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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