开发者

How to understand implementation of ntohs?

(gdb) disas htons
Dump of assembler code for function ntohs:
0x00000037aa4e9470 <ntohs+0>:   ror    $0x8,%di
0x00000037aa4e9474 <ntohs+4>:   movzwl %di,%eax
0x00000037aa4e9477 <ntohs+7>:   retq 

What does ror a开发者_Go百科nd movzwl do here?


ror stands for "rotate right", and movzwl stands for "move, zero-extending word to long" (for historical reasons dating all the way back to the 8086, in all x86 documentation "words" are only 16 bits).

So:

ror     $0x8, %di

Rotate the 16-bit value in register di (which, on x86-64, contains the first integer argument to a function) right by eight bits; in other words, exchange its high and low bytes. This is the piece that actually does the job of ntohs.

movzwl  %di, %eax

Copy the 16-bit value in di to eax, zero-extending it to a 32-bit value. This instruction is necessary because a function's integer return value goes in eax, and if it's shorter than 32 bits, must be extended to 32 bits.

retq

Return from the function. (The q is just a clue that you're on x86-64.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜