开发者

check if a register value is even/odd in MIPS

I tried to do 开发者_JAVA百科the following:

                        # with $s6 holding i+j
andi $s7, $s6, 0x1      # (i + j) & 1 (to check if it's even)
if: bneq $s7, $zero, else

however it generates an error... am I doing something wrong?


Perhaps your assembler doesn't like 0x1 integers?

andi $s7, $s6, 1
bnez $s7, odd         # branch if not-equal to Zero.

Or if your assembler doesn't like ABI names for registers, use register numbers?

andi $23, $22, 1      # $22=$s6  and   $23=$s7

If you use MARS or SPIM Simulator, or clang or other normal MIPS assemblers,
andi $s7, $s6, 0x1 assembles just fine.


Note andi doesn't add anything, so the i+j comment doesn't match

andi Rdest, Rsrc1, Imm
Put the logical AND of the integers from register Rsrc1 And Imm into register Rdest.


bneq does not exist.

Use

bne $s7,$zero,else

Post edit:

Heres a working example

  #include<mips/regdef>
    ...
    andi    t1,t1,0x1

Please add any error msg!


Following your question title, I thought this answer could be as useful to someone else as it was for me:

Since, for a binary value, if it ends with 0, it's even, if it ends with 1, it's odd. So, you basically need to get the first bit of a number with shift logical instructions like bellow.

sll $t0, $s0, 0x1F      
srl $s1, $t0, 0x1F 
  • s0 contains the value to be validated
  • t0 intermediates the shift operations
  • s1 has the final result (0 for even, 1 for odd)
  • Since each register has a value of 32 bits and we need just the first one, we shift the others 31 (0x1F) bits
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜