Assembly examples in wiki (xor vs. mov)

Programming, for all ages and all languages.
Post Reply
Andy1988
Member
Member
Posts: 50
Joined: Fri Aug 22, 2008 12:01 pm
Location: Germany - Aachen

Assembly examples in wiki (xor vs. mov)

Post 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
User avatar
Combuster
Member
Member
Posts: 9301
Joined: Wed Oct 18, 2006 3:45 am
Libera.chat IRC: [com]buster
Location: On the balcony, where I can actually keep 1½m distance
Contact:

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

Post 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))
"Certainly avoid yourself. He is a newbie and might not realize it. You'll hate his code deeply a few years down the road." - Sortie
[ My OS ] [ VDisk/SFS ]
Andy1988
Member
Member
Posts: 50
Joined: Fri Aug 22, 2008 12:01 pm
Location: Germany - Aachen

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

Post by Andy1988 »

Thank you.

These are all the nifty tricks that I have to learn ;)
User avatar
bewing
Member
Member
Posts: 1401
Joined: Wed Feb 07, 2007 1:45 pm
Location: Eugene, OR, US

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

Post 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.
Post Reply