Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 编写一个MIPS程序,测试一个数字是否是二的幂_Loops_Mips - Fatal编程技术网

Loops 编写一个MIPS程序,测试一个数字是否是二的幂

Loops 编写一个MIPS程序,测试一个数字是否是二的幂,loops,mips,Loops,Mips,编写一个MIPS程序,测试一个数字是否是二的幂。将寄存器$t0设置为SPIM中的某个值,并使用该值测试2的幂。程序将在控制台中生成输出 35不是二的幂 256是二的幂 到目前为止,我有这个 .data spc1: .asciiz " " nl: .asciiz "\n" tb: .asciiz "\t" msg1: .asciiz "is not a power of two." msg2: .asciiz "is a

编写一个MIPS程序,测试一个数字是否是二的幂。将寄存器$t0设置为SPIM中的某个值,并使用该值测试2的幂。程序将在控制台中生成输出

35不是二的幂

256是二的幂

到目前为止,我有这个

    .data

    spc1:   .asciiz " "
    nl:     .asciiz "\n"
    tb:     .asciiz "\t"
    msg1:   .asciiz "is not a power of two."
    msg2:   .asciiz "is a power of two."

    .text    # "text section" code and read-only data

    .globl main # declare `main' as a global symbol

    main:   #sra $t1, $t0, 1
    li $t1, 1
    loop:   beq $t0, $t1, end
    sra $t0, $t0, 1
    j loop
    end:    la $a0, msg2
    li $v0, 4
    syscall
    addi $v0, $0, 10
    syscall

我在模拟器中设置了$t0,这样就可以了。但不管我把它设成什么数字,我都会得到“是二的幂”。我正在使用shift left,但这一直给我错误的答案。如何正确使用shift来回答此问题?

在将
$t1
初始化为1后,应在每个循环迭代中对
$t1
执行左移位。
$t1
寄存器在每次循环迭代中等于2的新幂


如果
$t1
等于
$t0
,则应分支出循环。这种情况下,
$t0
是2的幂。如果左移后
$t1
变为0,则
$t0
不是2的幂。

有一种更简单的方法来测试数字是否是2的幂。在C伪代码中:

bool is_power_of_two(unsigned int number) {
    return (number & (number - 1)) == 0;
}
这是因为2的幂将以二进制形式表示
000…010…0
,小于1的数将以二进制形式表示
000…001…1
。也就是说,2的幂正好有一个位集,而数字1比它之前的每一个位都小。因此,这些数字之间的按位AND将为零,因为它们没有共同的设置位。每隔一对连续数字将共享一些共同的设置位,因此它们之间的按位AND不会为零

(请注意,此算法将告诉您1是2的幂。这是正确的:2到0的幂是1!)


由于这显然是一个类分配,我让您自己将其转换为MIPS代码。:)

sra
是向右移位,而不是向左移位。由于我们在每个循环迭代中都在
$t1
中存储了一个新的2次幂,因此在
$t0
不是2次幂的情况下,我们的分支语句将更正确
bgt$t1,$t0,而不是
,因为没有搜索大于输入的2个数字的幂的点
beqz$t1,不
也可以,但对于$t05,我们只需要检查024,而不是检查时的0到2^30。