以计算一个数的二进制重新presentation的1的数目最佳方式。 (MIPS) [英] Best way to calculate number of 1's in the binary representation of a number. (MIPS)

查看:184
本文介绍了以计算一个数的二进制重新presentation的1的数目最佳方式。 (MIPS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算在一个二进制数的1的数,可以说5,所以00001001将是2或n = 2。我使用MIPS。要做到这一点的最佳方式?

I need to calculate the number of 1's in a binary number, lets say 5, so 00001001 would be 2 or n=2. I am using MIPS. Best way to do this?

推荐答案

要做到这一点,最好的办法是的计数的他们。

The best way to do this is to count them.

如果最低显著位设置您可以检查(A 1 )通过一个ING它。如果你得到一个非零的结果,它被设置,所以你应该增加一个计数器(最初初始化为当然为零)。

You can check if the least significant bit is set (a 1) by anding it with one. If you get a non-zero result, it was set, so you should increment a counter (that was originally initialised to zero of course).

您可以通过正确使用逻辑缩骨运营商价值的所有位移动。

You can shift all the bits of a value right by using logical shifty operators.

您可以循环做这两个动作,直至你的价值为零结束。有大多数架构条件转移指令。

You can loop doing both those operations until your value ends up as zero. There are conditional branch instructions in most architectures.

你的任务的话,是要找到MIPS这些指令,并把它们按正确的顺序: - )

Your task, then, is to find those instructions for MIPS and put them in the correct order :-)

在没有特定的顺序,我会寻找到下面的一组指令: {岸堤,SRL,BEQ,ADDI} ,虽然可能有少数人你所需要的。

In no particular order, I'd be looking into the following set of instructions: {andi, srl, beq, addi}, though there may be a few others you'll need.

这篇关于以计算一个数的二进制重新presentation的1的数目最佳方式。 (MIPS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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