MIPS assembly not shifting correctly


I am currently working on a homework assignment, which is insert a bit value (0x0 or 0x1) into nth position.

.macro insert_to_nth_bit($regD, $regS, $regT, $maskReg)
    # regD:    bit pattern in which to be inserted at nth position
    # regS:    position n ( 0-31)
    # regT:    the bit to insert ( 0x0 or 0x1)
    # maskReg: temporary mask
                                    # Let's say regD = 00000101
    sllv $maskReg, $maskReg, $regS  # Let's say regS = 2, the second position at regD(0)
                                    # maskReg = 00000010 after shifting
    not $maskReg, $maskReg          # maskReg = 11111101
    and $regD, $regD, $maskReg      # regD = 00000101
    sllv $regT, $regT, $regS        # regT = 00000001, we want to insert 1 into the 2nd position at regD
                                    # regT = 00000010 after shifting
    or $regD, $regD, $regT          # 00000101 OR 00000010 = 00000111. The bit is what i wanted 

Here's the macro I wrote to test it

.globl main
la  $t0, 0x00000101 #t0 = 00000101
la  $t1, 2      # nth position = 2
la  $t2, 0x1    # insert 0x1
la  $t3, 1      # maskReg = 00000001
insert_to_nth_bit($t0, $t1, $t2, $t3)

print_int and exit are two other small macros

The result that I get is 261, which is 00000105 after I converted to hex. When I debug it, I noticed that when it comes to the first shift, the 00000001 and shift left 2 becomes 00000005, which mess up the whole thing. I wonder if the logic of my macro is wrong or the way I test my macro is wrong so it messed out my output?

asked on Stack Overflow Nov 27, 2016 by user21478621 • edited Nov 27, 2016 by Michael

1 Answer


Your macro is correct, based on context.

But, maskReg needs a one. You're presetting this outside the macro. And, you're using la to initialize constant values. li would be the more usual choice.

I'd remove the la $t3,1 and add li $maskReg,1 as the first line of the macro.

That's the whole point of macros: to reduce the number of repetitive steps.

answered on Stack Overflow Nov 27, 2016 by Craig Estey • edited Nov 27, 2016 by Craig Estey

User contributions licensed under CC BY-SA 3.0