Hello everyone, I am new in assembly programming for MIPS and I was given a project to write a program that converts any decimal bumber from 0 to 511 into octal and return the result with 3 digits in reverse i.e. 170 for the decimal 57, 026 for 400 and so on. I was given the following code to work with which converts decimal number 30 to binary. Can anyone please help? Thanks in advance

addi $9, $0, 30
addi $10, $0, 5
addi $2, $0, 1
L1:
and $4, $9, $2
syscall
srl $9, $9, 1
addi $10, $10 -1
bne $10, $0, L1

Dani AI

Generated

Nice find, . Your div/rem loop nails the assignment requirement: printing three remainders base-8 yields a fixed-width, reversed octal result (e.g., 400 -> 026). Also, in your first attempt, setting $v0 ($2) to 1 makes syscall print the integer in $a0 ($4) each iteration. Small syntax note: some assemblers expect a comma in addi $10, $10, -1.

If you want a branch-free divide alternative, remember that 0..511 fits in 9 bits, so each octal digit is just a 3-bit chunk. Mask and shift instead of dividing:

# read n (0..511), then print three reversed octal digits
li   $v0, 5           # read_int
syscall
move $s0, $v0
andi $s0, $s0, 0x1FF  # clamp to 9 bits (optional)

li   $t1, 3           # digit count
li   $v0, 11          # print_char
li   $t2, 48          # ASCII '0'

oct3:
  andi $t0, $s0, 7    # low 3 bits
  addu $a0, $t0, $t2  # to ASCII
  syscall
  srl  $s0, $s0, 3    # move to next octal digit
  addi $t1, $t1, -1
  bgtz $t1, oct3

# newline
li   $a0, 10
syscall

A couple of practical tips tied to your posts:

  • Want normal (non-reversed) octal instead? Either store the three digits and print them in reverse, or extract MSB-first by shifting 6, then 3, then 0 bits before masking.
  • If you keep print_int (syscall 1) as in your snippets, it still works because each remainder is 0..7. print_char (syscall 11) is cleaner for single digits.
  • Ensure logical shifts (srl) are used, not arithmetic (sra), so zeros are shifted in on the left.

Nevermind, I've had a revelation and found it myself. But for any of you that might have the same question I put the code here. Note that this is for decimal number 400 which is mentioned in the first string of the code.
Thanks again to those of you that read the post.

addi $9, $0, 400
addi $10, $0, 3
addi $2, $0, 1
L1:
div $5, $9, 8
rem $4, $9, 8
syscall
move $9, $5
addi $10, $10 -1
bne $10, $0, L1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.