校验和汇编算法没有加起来正确的值

时间:2013-09-26 08:54:55

标签: string debugging assembly mips checksum

我正在为MIPS程序集中输入的字符串实现基本校验和算法,作为使用该语言的一般介绍,我可以使用一些错误检查。

这是我到目前为止所做的评论,其中包含的评论是为了跟踪每一步发生的事情:

.data
str1:
    .asciiz "This is a short string."
cs1:
    .word   0x84a
str2:
    .asciiz "This is a much longer string.  In fact, it has two sentences in it, and some funny characters (~`)€."
cs2:
    .word   0x230a
NonSuccessString:
    .asciiz "You have more work to do."
Test1Success:
    .asciiz "Test 1 was successful.  "
Test2Success:
    .asciiz "Test 2 was successful.  "

.text
    la  $a0, str1 #Set $a0 to address of label str1:
    jal checksum #Set $ra to address of next instruction, then jump to label checksum:
    la  $s0, cs1 #Set $s0 to address of label cs1:
    lw  $s1, 0($s0) #Set $s1 to contents of memory address $s0
    beq $v0, $s1, Success1 # If $v0 and $sl are equal, jump to label Success1:
    j NonSuccess # Jump to label NonSuccess:
Success1:
    la  $a0, Test1Success #Set $a0 to address of label Test1Success:
    addi    $v0, $zero, 4 
    syscall
    la  $a0, str2 #Set $a0 to address of label str2:
    jal checksum #Set $ra to return address, then jump to label checksum:
    la  $s0, cs2 #Set $s0 to address of label cs2:
    lw  $s1, 0($s0) #Set $s1 to contents of memory address $s0
    beq $v0, $s1, Success2 # If $v0 and $sl are equal, jump to label Success2:
    j NonSuccess # Jump to label NonSuccess:
Success2:
    la  $a0, Test2Success #Set $a0 to address of label Test2Success:
    addi    $v0, $zero, 4
    syscall
    j Quit # Jump to label Quit:
NonSuccess:
    la  $a0, NonSuccessString #Set $a0 to address of label NonSuccessString:
    addi    $v0, $zero, 4
    syscall
Quit:
    addi    $v0, $zero, 10
    syscall

checksum:
        addi $sp, $sp, -4      # adjust stack for 1 item
        sw   $s0, 0($sp)       # save $s0
    add  $s0, $zero, $zero # i = 0
    L1:
        add $t1, $s0, $a0 # Locate the character at y[i]
        lbu $t2, 0($t1) # Load the unsigned byte value of y[i]
        beq  $t2, $zero, L2    # exit loop if y[i] == 0 
        add $v0, $v0, $t2 # Add the byte to the total value
            addi $s0, $s0, 1  # i = i + 1
        j L1
    L2:
        jr $ra #jump back to $ra

第一次测试中的简单字符串计算正确,我得到第一个“测试1成功”。消息,但在第二个校验和上,调试报告的总和为0x230e,比预期值多4个,这意味着发生了一些问题。我猜这些特殊字符可能导致了这个问题,但我不确定。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在计算校验和之前,您没有重置$v0add $v0,$zero,$zero标签前应该有L1:

但我仍然没有看到值0x230a的来源。在我看来,第二个字符串的正确校验和是0x22de。