我正在尝试将基数为 10 的输入转换为二进制,并尝试将其存储在 input_buffer 中,然后打印出 input_buffer。当我尝试不打印任何内容时,就好像它是空的以供参考,这就是我所拥有的:
.data
ask_input: .asciiz "Enter a number (0-255): "
binary: .asciiz "\nThe number in base 2 is: "
input_buffer: .space 10
.text
.globl main
main:
# Ask for input
li $v0, 4
la $a0, ask_input
syscall
# Assign input
li $v0, 5
syscall
move $s0, $v0 # Integer is stored in $s0
# Setup
li $t0, 2 # For dividing by 2
li $t1, 0 # For holding binary
li $t2, 8 # Assume 8-bit binary response
# Initialize the input_buffer with null bytes
li $t3, 0 # Null byte
li $t4, 10 # Number of bytes to initialize
la $t5, input_buffer # Address of input_buffer
initialize_buffer:
sb $t3, ($t5) # Store a null byte
addi $t5, $t5, 1 # Move to the next byte
addi $t4, $t4, -1 # Decrement the byte count
bnez $t4, initialize_buffer # Continue until all bytes are null
convert_loop:
# Continue the loop until $s0 is not equal to 0
bnez $s0, continue_conversion
# If $s0 is 0, jump to printing the binary
j print_bin
continue_conversion:
# Use 'and' with 1 for the least significant digit
andi $t3, $s0, 1
# Convert the least significant digit to '0' or '1'
addi $t3, $t3, '0'
# Store the ASCII character in input_buffer
sb $t3, input_buffer($t2)
# Right shift for division by 2
srl $s0, $s0, 1
# Decrement the counter
addi $t2, $t2, -1
# Continue the loop
j convert_loop
print_bin:
# Print the output message
li $v0, 4
la $a0, binary
syscall
# Print the binary representation stored in input_buffer
li $v0, 4
la $a0, input_buffer
syscall
# Exit
li $v0, 10
syscall
您将数字向后存储到缓冲区中。当输入值变为 0 时,转换循环就会停止。因此,对于 3 这样的输入值,它会存储 1,然后存储 1,然后停止。缓冲区看起来像这样:
0 0 0 0 0 0x31 0x31 0
^ ^
input_buffer t2 (as index)
然后从缓冲区的开头开始打印,该缓冲区为空,所以当然不会打印任何内容。用于打印字符串的系统调用 #4 在它看到的第一个 null 处停止,即它打印一个以 null 结尾的字符串。
您可以执行以下操作之一:
用空格 0x20 初始化缓冲区,而不是空值
这将打印前导空格,后跟 11,或者,
打印缓冲区,不是从头开始,而是从转换循环停止的地方开始
使用
la $a0, input_buffer+1($t2)
考虑到您要存储到缓冲区中,实际上没有必要用 null 来初始化它。如果您的算法精确地使用缓冲区,它将覆盖那里的任何旧值。