views:

565

answers:

1

hey, i need help. I have written this code in MARS. It is supposed to receive an integer from the user, and convert it to HEX. I've been going over it for hours and as far as i can see, it should work fine. I have only included the loop and output part of the program as this is the only part that is not working. Can someone PLEASE point out where the code is going wrong? Thank you.

P.S. I think it is messing up on the bit-by-bit AND, i used this to mask off the lower bits but for some reason it almost seems like it's ADDing not ANDing. :-(

   li $s1, 8              # Set up a loop counter

Loop:

   rol $s0, $s0, 4        # Roll the bits left by four bits - wraps highest bits to lowest bits (where we need them!)

   and $t0, $s0, 16        # Mask off low bits (logical AND with 000...01111)
   slti $t1, $t0, 10       # Determine if the bits represent a number less than 10 (slti)
   bne $t1, $zero, MakeLowDigit  # If yes (if lower than 9), go make a low digit

MakeHighDigit:

   subi $t0, $t0, 10            # Subtract 10 from low bits
   addi $t0, $t0, 64             # Add them to the code for 'A' (65), becomes a..f
   j DigitOut

MakeLowDigit:

   addi $t0, $t0, 47             # Combine it with ASCII code for '0', becomes 0..9

DigitOut:

    move $a0, $t0         # Output the ASCII character
    li $v0, 11
    syscall

    subi $s1, $s1, 1            # Decrement loop counter
    bne $s1, $zero, Loop        # Keep looping if loop counter is not zero
+1  A: 

You're at least masking with the wrong constant:

and $t0, $s0, 16               # Mask off low bits (logical AND with 000...01111)

The integer 16 has the bit pattern ...010000, i.e. it very much does not end in four ones. You want 15, i.e. 16 - 1.

In general, to create a right-adjusted bit-mask with n bits set, you need to compute 2n-1, which in C notation is (1 << n) - 1.

unwind