'Copy bit of one register to another register (x86-64 asm)

as part of a project that generates x86-64 machine code at runtime, I very often have the need to copy a bit from one register to another register at another bit position.

I came up with this code (example that copies bit 23 of a source register to bit 3 of a destination):

bt eax, 23           ; test bit 23 of eax (source)
setc ebx             ; copy result to ebx (ebx is guaranteed to be zero before)
shl ebx, 3           ; shift up to become our target bit 3
and ecx, 0xFFFFFFF7  ; remove bit 3 from ecx (target)
or ecx, ebx          ; set new bit value

Given that I need five instructions just to copy one bit of one register to another bit of another register, I thought if there is something that uses less instructions on x86?

I've read a bit on BMI instructions but unfortunately they do not offer bit extraction using immediates.



Solution 1:[1]

Alternative:

        rcr     ecx,3+1
        bt      eax,23
        rcl     ecx,3+1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1