解析int作为字符串的字符串
在MIPS程序集中,我将如何将诸如255的整数解析为字符串'2''5''5'的字符串。解析int作为字符串的字符串
255可以是在T 0
“2''5''5”然后可以被存储在t1和随后进行打印。
我该怎么做?
以下是Python中的版本。只需将其翻译成mips组件即可。
def to_str(n):
output = ''
while True:
m = n % 10
output = str(m) + output
n = n/10
if n == 0:
break
print(output)
这个想法是通过碱基(在这种情况下为10)重复获得除法余数。 例如:
n = 255
n % 10 -> 5, n = 255/10 = 25
n % 10 -> 5, n = 25/10 = 2
2 % 10 -> 2, n = 2/10 = 0
现在,刚刚获得师余并以相反的顺序打印出来。
以下是在MIPS组件的一个解决方案:
.data
N: .word 2554
digits: .space 16 # number of digits * 4 bytes
num_digits: .word 3 # number of digits - 1
.text
lw $t0, N # $t0 = N
lw $t1, num_digits
sll $t1, $t1, 2
la $s0, digits
add $s0, $s0, $t1
loop:
div $t2, $t0, 10
mfhi $t2 # remainder is in $t2
sw $t2, 0($s0)
subi $s0, $s0, 4
div $t0, $t0, 10
beqz $t0, print
b loop
print:
# print contents of digits
li $t0, 0 # loop counter
lw $t1, num_digits
la $s0, digits
print_loop:
bgt $t0, $t1, end
# print the digit
lw $a0, 0($s0)
li $v0, 1
syscall
# put a space between digits
la $a0, 32
li $v0, 11
syscall
# move the next digit and increment counter
addi $s0, $s0, 4
addi $t0, $t0, 1
b print_loop
end:
这导致下面的输出:
2 5 5 4
-- program is finished running (dropped off bottom) --
转换数目为一个字符串在另一个基站的想法基本上重复除法它由基地,在这种情况下,10,并向后写余下。这是最简单的解决方案。
对于十进制你有另一个选择,那就是double dabble,它可以二进制转换成压缩BCD没有分裂。从此你可以解开半字节到字符
的Asterisk做了很好的工作!我只是在写信让他的答案更加完整。
消息
-- program is finished running (dropped off bottom) --
显示,因为他并没有结束他的节目与
li $v0, 10
syscall
你应该总是与上述各行完成你的程序正常终止执行。
从http://logos.cs.uic.edu/366/notes/mips%20quick%20tutorial.htm:
e.g. To indicate end of program, use exit system call; thus last lines of program should be:
li $v0, 10 # system call code for exit = 10
syscall # call operating sys
为什么不赞成票他,如果他做了这样一个伟大的工作吗?另外,这应该是对他的答案的评论 - 它本身并不回答这个问题。 –
我不能评论,因为我的声望在50以下。我只能在这里发表评论,我不知道为什么。 – gon1332
你想要的字符的8位ASCII版本储存背到后面T1内? – Kat
你是指整数还是字节? 32位给你4个ASCII码字符 –
@TonyHopkinson我想从t0得到255,并说2或值0x32,因为这是t1的字符值,然后做同样的5可以放在t2然后其他5在t3 – user3093146