Search code examples
assemblyx86

Is it possible to swap the most significant bit and the least significant bit of a register in x86 assembly without using conditional jumps?


Here is how it is done in PicoBlaze assembly:

;This is an example program written by
;Agustin Izaguirre in the issue #9. It
;switches the least significant bit and the
;most significant bit without using jumps.

address 0

load s0,59
output s0,0

;shift and load MSB into an aux register
sl0 s0
output s0, 0
addcy s1, 0

;shift back again and load LSB into an aux register
sr0 s0
output s0, 0
sr0 s0
output s0, 0
addcy s2, 0

;load MSB aux reg into carry so that we can SLA in the bit
sr0 s1
sla s0
output s0, 0

;shift back and load LSB aux reg into carry so that we can SRA in the bit
sl0 s0
output s0, 0
sr0 s2
sra s0 ;bugged line, should be shifting the C flag from the left
output s0, 0

Is it possible to do that in x86 assembly as well? If so, how?

x86 has no equivalent of the sra instruction, right? So, how can it be simulated without using conditional jumps?


Solution

  • Here's a simple way to do it, assuming eax holds AXX...XB initially:

    rol eax, 1 ; EAX = XXX...XBA, CF = A
    bt  eax, 1 ; EAX = XXX...XBA, CF = B
    rcr eax, 2 ; EAX = ABXXX...X, CF = B
    rol eax, 1 ; EAX = BXXX...XA, CF = A