I thought it was strange when I was looking at the code below. The first instruction clearly has completed the task of data transfer and expansion into 16 bits. Why is there a "mov Eax,ax" in the assembly code?

    movzx   eax, word ptr [rbp+addr.sa_data]
    movzx   eax, ax
    mov     edi, eax
    call    _htons

1 Answer 1


Obviously the movzx eax, ax is useless. I would say this is unoptimized code, this C code could reproduce the same generated code.

#include <stdint.h>

void f(uint16_t v)

struct S
        uint16_t a;

int main(void)
        struct S s;
        s.a = 0x1122;
        return 0;

Compiling with gcc without optimization options, the code is:

1134:       0f b7 45 fe             movzx  eax,WORD PTR [rbp-0x2]
1138:       0f b7 c0                movzx  eax,ax
113b:       89 c7                   mov    edi,eax
113d:       e8 d7 ff ff ff          call   1119 <f>

Note, I wasn't able to produce the same result neither with clang or vc++. Besides, it only happens when the value is read from a structure.

  • I think it's because I took the data from the addr structure and produced this code. Thank you for your answer.
    – RT zhou
    Dec 22, 2018 at 11:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.