Search code examples
assemblyx86

Assembly x86, mov $constant, %register


I have the following code snippet:

mov $0, %eax
mov $0x2023, %ax
mov $1, %ah

What happens when mov $0x2023, %ax is executed?

I expected %eax=0x20231 but it is 0x123. I've used a debugger and saw that %ax was 0x2023, but %ah becomes 20 and %al becomes 23. Why does this happen? Below is how I thought the code will run.

mov $0, %eax # eax = (AX)0000000000000000  (AH)00000000  (AL)00000000
mov $0x2023, %ax # eax = (AX)0010 0000 0010 0011  (AH)00000000  (AL)00000000
mov $1, %ah # eax = (AX)0010 0000 0010 0011  (AH)00000001  (AL)00000000

Solution

  • EAX is not composed of AX, AH, and AL the way you think!

    See How do AX, AH, AL map onto EAX?

                         high end     low end
                         |            |
                         v            v 
                         <---  EAX --->
    mov $0, %eax         00  00  00  00 
    
                                 <-AX->
    mov $0x2023, %ax     00  00  20  23
    
                                 AH  AL
    mov $1, %ah          00  00  01  23
                         <-??->
    

    No name was given to the ?? part that runs from bit 16 to bit 31.
    Personally, I regularly call it AXE.