我想在.asm中创建一个子程序,可以查看终端中给出的数字是否是2的平方。
即:我选择数字5,是2 ^ x = 5?我的子程序将进行几个分区来检查除法的其余部分是0还是1,这就是告诉我5是否是2的平方。
例如,在C中我写了这段代码:
int square(int val){
while (((val % 2) == 0) && val > 1)
val = val/2;
if(val == 1)
return 1;
else
return 0;
}
汇编中的等价物是什么?
答案 0 :(得分:-2)
鉴于您没有为asm指定特定的编译器,我将为您发布asm51编译器的示例,用于intel uC 8051:
org 00H ;start directive
VAL equ R2 ;assuming that value of interest is in R2 register
COUNTER equ R3
mov COUNTER,#8D ;initialise the counter
mov A,VAL ;store in the accumulator
;the value you want to check if is power of two
LOOPi: jb Acc,7,NEXT ;if bit 7 of value is 1 jump to NEXT tag
LOOPj: rl A ;rotate bit 7 of acumulator to left
djnz COUNTER,LOOPi ;decrease COUNTER and check another bit if counter != 0
jmp FINISH ;jump to finish if counter == 0
NEXT: inc COUNTER
jmp LOOPj
FINISH:cjne COUNTER,#1D,SOME ;if counter == 1 then value is power of 2
;;;;;;here you do whatever you have to do if is power of two
SOME:
;;;;;;here you do whatever you have to do if it is not power of two
基本上我在这里做的是检查我的8位中只有一个1的情况,如果是这种情况我有2的幂:
<强>记住:强>
0000 0001 = 1 = power(2,0)
0000 0010 = 2 = power(2,1)
0000 0100 = 4 = power(2,2)
0000 1000 = 8 = power(2,3)
0001 0000 = 16 = power(2,4)
0010 0010 = 32 = power(2,5)
0100 0010 = 64 = power(2,6)
1000 0000 = 128 = power(2,7)
正如您可能已经注意到的那样,此示例仅限于7个2的幂,但由于寄存器的大小,这对于其他架构会有所不同,在这种特殊情况下,8051寄存器仅为1个字节。 希望能帮助到你。 干杯