Search code examples
assemblyx86x86-emulation

I want to swap the position of two bits. How to do this?


I am given a question in which I have to write a program such that the last bit of the offset address of the first segment becomes the first bit of the offset address of the second segment. For example if I am given ABCDH then the offset address of the second address should be DCBAH. I am just focusing on the swapping of the offset address and am ignoring the base address for now:

MOV AX,ABCDH
ROR AX,16  ;    this will rotate the value of AX 16 times

Now we have CDABH. Now I want to swap the position of D and C. I am stuck at this point. Will I use SAR command?


Solution

  • MOV AX,ABCDH
    ROR AX,16  ;    this will rotate the value of AX 16 times
    

    Now we have CDABH

    The AX register holds 16 bits. When you rotate these 16 bits 16 times you get the same value that you started with!

    For example if I am given ABCDH then the offset address of the second address should be DCBAH

    So you want to go from ABCDh to DCBAh.

    The AX register is subdivided in 2 halves. The low half is named AL and the high half is named AH. You can operate on these halves independently.

    The instruction mov ax, 0ABCDh puts the value 0ABh in AH and puts the value 0CDh in AL.

    mov     ax, 0ABCDh  ; AH = 0ABh AL = 0CDh
    rol     al, 4       ; AH = 0ABh AL = 0DCh 
    rol     ah, 4       ; AH = 0BAh AL = 0DCh
    xchg    al, ah      ; AH = 0DCh AL = 0BAh
    

    Now finally AX=0DCBAh.


    All of the above deals with 4-bit quantities. We call these nibbles.
    You can write your hexadecimal value 0ABCDh using the binary representation like 1010101111001101b. You can see that there are 16 bits.

    Aligned groups of bits have special names:

    • every 4 bits form a nibble, you can see that there are 4 nibbles. (1010 1011 1100 1101)
    • every 8 bits form a byte, you can see that there are 2 bytes. (10101011 11001101)
    • every 16 bits form a word, you can see that there is 1 word. (1010101111001101)