Sparc机器基本组装,计数位

时间:2012-10-08 04:17:25

标签: assembly counting sparc

所以我需要计算一个整数上的位这是我的代码,但我不知道为什么不工作,我从c main发送了一个十六进制值,不知何故我必须移动它并掩盖它。我有点迷茫,我想我得到了一个错误的答案,因为我不知道如何移动和掩盖,但我想我知道我正在做的循环和添加。再次,我需要计算直到32位1不是零,但我得到一个错误的答案,例如6 110它将是2位。这是一个功课,所以我不能使用内置功能或任何哈哈。

   .global hi
hi:

save %sp,-1024,%sp

clr %i0
clr %i1
clr %i2

loop:  

       cmp %i2,32
       be,a away
    mov %l7,%i0
    add 1,%i2,%i2

    and %i0,1,%l1


    cmp %l1,1
    be count
       nop
    !srl %i0,%l2,%10
    !mov %l2,%i0


    !and %i0,1,%i0
    srl %i0,1,%i0

    ba loop
    nop
    !mov %l2,%i0

count:
    add 1,%l7,%l7

away:
    ret
    restore

为什么这不起作用?我遵循它的c实现,仍然没有返回位数:/。返回值是%i0,我不知道如何在递增计数器后跳回循环。

那是做什么的?当它说ba循环不是它应该回到循环?

所以我不知道是否要问很多但你知道如何解决这个问题吗? :p因为我真的不知道,我正在查看手册,我看不到任何可以帮助我的东西:/。

1 个答案:

答案 0 :(得分:0)

移位和添加也有错误......

您的循环结构大致如下:

int count(int data) {
loop_entry:
        if (loop_counter == 32) goto out;      // this is basically ok
        loop_counter++;            

        if (some_math_expression) goto count;  // the math expression is ok

        temporary_variable>>=1;   // this is not ok -- you should be shifting l2 

        if (something_else) goto loop_entry;   // what actually is the 'something_else'?

count:
        data++;    // this is not ok: you are incrementing i0 instead of l2
                   // this is not ok: fall through instead of jumping back to loop

out:
        return result;

}

与C中的实现最接近的正确结构将是

int count (int data)
{
     int result=0;
     int temp=0;
     int loop_counter = 0;
     while (loop_counter++ != 32) {  // conditionally jump out of the loop
         temp = data & 1;
         if (temp == 1) {   // Q: how to perform this in assembler? 
            result++;       // A: negate the condition and jump over the result++
         }                  // statement
         data>>=1;
     }                      // (unconditionally? Jump to beginning of loop)
     return result;
}

http://www.cs.northwestern.edu/~agupta/_projects/sparc_simulator/SPARC%20INSTRUCTION%20SET-1.htm

这里说'ba'=分支总是(我的错误) - 如果(temp == 1)的比较是由'be'完成的,或者如果相等则是branch,那么相反的是 如果不相等,那就是分支,或者是。因此,条件限制将是:

cmp %temp, %one          # I'm using temp & one to "alias" the registers
bne skip                 # that contain these variables or constants
nop    ; // delay slot
add %count, 1, %count
skip:

// there's however a trick to do that without jumping (see the link about 'carry'-bit)
add %data,%data,%data    # "multiply" data by two, which may produce carry
addx %count,%zero,%count # count = count + 0 + carry_produced_by_previous_instruction

Reason to use the carry bit and the overflow bit