microprocessorsrisc

How to perform right shift on RISC


I'd like to know how I can perform a right shift on a Reduced Instruction Set Computer that does not offer this operation on it's own.
A left shift can be simply done by adding a register to itself but how about a right shift?

The RISC offers only:

ADD 
NOT
NXOR (XOR)
AND (NAND)

so OR and NOR can all be emulated by several (N)AND and NOT operations.


Solution

  • The C program below uses only authorized instructions plus conditional jumps, and it shifts input into output by 1.

    If the instruction you are trying to emulate is “shift by n”, then you should start with c equal to 2n.

    unsigned int shift_right(unsigned int input) {
      unsigned int d = 1;
      unsigned int output = 0;
      for (unsigned int c = 2; c <= 0x80000000; c += c)
      {
        if (c & input) 
          output |= d;
        d += d;
      }
      return output;
    }