Page 1 of 1

Assembly examples in wiki (xor vs. mov)

Posted: Fri Aug 22, 2008 12:08 pm
by Andy1988
Hi there,
first of all I have to say that this wiki is great. I was always interested in doing some more with assembly language and the whole low level x86 architecture. This wiki helped me a lot in the last few days.

But I always read something like this in the examples in the wiki to set a register to zero:
"xor ax, ax"

Why? Yes, it does what it is supposed to do and I also know why, but why do you always use xor insted of mov?
"mov ax, 0" will do its job too, wouldn't it?

Do you use xor because it takes less cpu cycles? That's the only reason that came into my mind for this.

Thanks for your answers,
Andy

Re: Assembly examples in wiki (xor vs. mov)

Posted: Fri Aug 22, 2008 12:26 pm
by Combuster
XOR requires fewer bytes, for not having a constant appended to the instruction.

xor eax, eax = 2 (opcode(1) + modrm(2))
mov eax, 0 = 5 (opcode(1) + constant(2-5))

Re: Assembly examples in wiki (xor vs. mov)

Posted: Fri Aug 22, 2008 1:11 pm
by Andy1988
Thank you.

These are all the nifty tricks that I have to learn ;)

Re: Assembly examples in wiki (xor vs. mov)

Posted: Fri Aug 22, 2008 4:08 pm
by bewing
Also, the inputs to the XOR function are both registers. One of the inputs to MOV in this case is an "immediate" value that has to be loaded out of cached memory, then passed down into the "execution engine". So yes, theoretically the XOR instruction may involve slightly less "work" for the cpu, and on some architectures may run faster.
The only way things could be better than using XOR would be a 1 byte "CLR" opcode that sets a register to 0. Motorola chips had an opcode for that, but the intel chips never did.