Search code examples
assemblyx86bit-manipulationmicro-optimization

How to exchange between 2 bits in a 1-byte number


I have a byte-sized number in register AL (8 bits), in 32-bit x86.

I need to exchange between bit 1 (the second from right) and bit 4 (the fifth from right) of the number in register AL.

For example

00010000B    input
00000010B    output

Solution

  • You may try this:

    mov BL, AL
    mov BH, AL
    
    and BL, 2h   //empty all bits except first
    and BH, 10h  //empty all bits except fourth
    
    shl BL, 3    //move bit 1 to position of bit 4
    shr BH, 3    //move bit 4 to position of bit 1
    
    and AL, edh  //empty first and fourth bits
    or AL, BL    //set bit 4
    or AL, BH    //set bit 1
    

    AL register contains the result. Also you may need data stored in register BX. If you do then prepend solution with

    push BX
    

    end append to the end

    pop BX