assemblybit-shiftz80

How to rotate a 16-bit register in Z80


I have a value in a 16-bit register (say, HL). How do I rotate it left one or more times?


Solution

  • The Z80 can rotate an 8-bit register perfectly using the RL m instruction, with the help of the carry bit. First, the register is rotated left, placing the carry value in bit 0 and then leaving bit 7 in the carry.

    The rotate left operation

    To rotate a pair of registers (HL, for example), you must rotate H and then L separately.

    To rotate H, you must first place bit 7 of L in the carry. This is achieved by copying L to the accumulator and then rotating it with RLA. After that, rotate register H with RL H(which put the carry in bit 0 and then leaves bit 7 in the carry), followed by RL L.

       ld  a, l
       rla
       rl  h   
       rl  l
    

    The process is repeated for each position you want to rotate.

    If you are rotating more than one position, you can optimize this by copying L to the accumulator only once, but this only works for rotate less than 8 positions.

    Example: rotate HL two positions to the left:

       ld  a, l
    
       rla
       rl  h   
       rl  l
    
       rla
       rl  h   
       rl  l