SHRD : A Ruby Interpretation of the Double Precision Shift Right Assembly Instruction

Following on from my last post on Assembly conversion, I also came across the SHRD instruction.

I already knew about the SHR & SHL command, logical shift right & left respectively, which translates rather easily:

AssemblyRuby
1
shr @ax, 5
1
@ax >>= 5
1
shl @ax, 5
1
@ax <<= 5

But I was initially stumped when I saw

1
shrd ax, dl, cl

in the Assembly code listing.

I’d figured out I needed the following test data, from the debugger

1
2
3
def test_shrd
  assert_equal 12927, shrd(40919, 140, 6)
end

And then this link gave me the insight I needed to code it up.

Voila:

1
2
3
4
5
6
#see https://en.wikibooks.org/wiki/X86_Assembly/Shift_and_Rotate#Extended_Shift_Instructions for more info on shrd
def shrd(rm16, r16, cl)
  rm16 >>= cl
  r16 <<= (16 - cl)
  rm16 | (r16 & 0xFFFF)
end

The test went from red to green :)

They will not control us. We will be victourious!!!!!!”

:D

Comments