MIPS Bitwise Operators

Introduction

MIPS supports several bitwise logical operators. There are the list of the R-type logical bitwise operators. Here are the list of the I-type logical bitwise operators.

Example and Semantics

The generic form for the R-type bitwise logical operators. are:
and $rd, $rs, $rt
or  $rd, $rs, $rt
nor $rd, $rs, $rt
xor $rd, $rs, $rt
Interesting enough, MIPS does not support bitwise negation (this can be performed with two instructions: setting a register's value to -1 with addi and using xor on the register to be negated and the register with -1 in it, which is storing all 1's).

Also, MIPS has a NOR instruction, but not a NAND instruction.

The semantics of the bitwise operators should be obvious enough.

Here are the immediate version of the operators.

andi $rt, $rs, immed
ori  $rt, $rs, immed
xori $rt, $rs, immed

Notice there's no nori.

The semantics are a little more complicated, so we'll write it for andi below where & stands for bitwise AND.

 R[t] <- R[s] & 016::IR15-0

Logical operators treat the immediate value as a bitstring, not as an unsigned value. So, it makes more sense to zero-extend the immediate value from 16 bits to 32 bits. Thus, the upper 16 bits of the zero-extended immediate contain all zeroes.

Machine Code Representation

Here are the representations for R-type bitwise logical operators.

Instruction B31-26 B25-21 B20-16 B15-11 B10-6 B5-0
  opcode register s register t register d shift amount function
and $rd, $rs, $rt 000 000 (SPECIAL) - - - 00000 100 100
or $rd, $rs, $rt 000 000 (SPECIAL) - - - 00000 100 101
nor $rd, $rs, $rt 000 000 (SPECIAL) - - - 00000 100 111
or $rd, $rs, $rt 000 000 (SPECIAL) - - - 00000 100 110

Here are the representations for I-type bitwise logical operators.

Instruction B31-26 B25-21 B20-16                 B15-0                
  opcode register s register t immediate
andi $rt, $rs, <immed> 001 100 - - -
ori $rt, $rs, <immed> 001 101 - - -
xori $rt, $rs, <immed> 001 110 - - -

The dashes are 5-bit encoding of the register number in UB. For example, $r7 is encoded as 00111. The rightmost dash is a 16-bit immediate value written in UB.