我发现这段代码片段我认为会将整数转换为十六进制。但是,我根本不关注它。我添加了评论说我认为发生了什么,但我不知道为什么要这样做。所以,假设我正确地注意到每条线路正在做什么,有人可以向我解释为什么要这样做吗?如何以任何方式帮助转换为十六进制?
$ a0是整数值
$ a1是结果应该在哪里的地址
addi $t0, $0, 48 #set $t0 equal to 48
sb $t0, 0($a1) #store $to (48) at location 0 in $a1
addi $t0, $0, 120 #set $t0 equal to 120
sb $t0, 1($a1) #store $t0 (120) at location 1 in $a1
addi $t1, $a1, 9 #set $t1 = the address + 9
LOOP:
andi $t0, $a0, 0xf #$t0 = 1 if $a0 and 0xf are the same (0xf = beginning of hex)?
slti $t2, $t0, 10 #if $t0 is less than 10, $t2 = 1, else 0
bne $t2, $0, DIGIT #if $t2 does not equal 0, branch to DIGIT
addi $t0, $t0, 48 #set $t0 equal to 48
addi $t0, $t0, 39 #set $t0 equal to 39 (why did we just write over the 48?)
DIGIT:
sb $t0, 0($t1) #set $t0 equal to whatever's in location 0 of $t1
srl $a0, $a0, 4 #shift right 4 bits
bne $a0, $0, LOOP #if $a0 does not equal 0, branch to LOOP
addi $t1, $t1, -1 #set $t1 = $t1 - 1
DONE:
jr $ra #set the jump register back to $ra
nop
答案 0 :(得分:1)
slti $t2, $t0, 10 #if $t0 is less than 10, $t2 = 1, else 0
bne $t2, $0, DIGIT #if $t2 does not equal 0, branch to DIGIT
addi $t0, $t0, 48 #set $t0 equal to 48
addi $t0, $t0, 39 #set $t0 equal to 39 (why did we just write over the 48?)
MIPS使用分支延迟时隙,这意味着分支指令之后的指令总是在分支被采用(或不被采用)之前执行。
所以这就是说“如果$ t0小于10(即在0..9范围内),转到DIGIT,但不管$ t0的值如何,首先加48(ASCII'0')。分支被取出你现在已经从0..9转换为'0'..'9'。如果没有采取分支,$ t0最初在10..15范围内,现在将在范围58..63,所以我们再添加39个以获得97..102范围内的值('a'...'f'的ASCII代码)“。