I'm trying to write a boot loader, and all the code I am writing is being run in real mode. In all the examples I find there is either an xor ax, ax or xor eax, eax, and I don't understand what this is doing. It seems to have something to do with setting up the segment registers, but I am unclear as to what.
Asked
Active
Viewed 7,781 times
2
ragingSloth
- 1,094
- 8
- 22
-
1http://stackoverflow.com/questions/8201676/xor-register-register-assembler?rq=1 – phuclv Oct 30 '14 at 08:49
-
1AX and EAX are not segment registers. Segment registers are registers ending with s like GS, FS, DS, ES... – phuclv Nov 01 '14 at 05:45
2 Answers
3
Xor instruction is Exclusive OR
Check out the exclusive OR truth table XOR
xor eax, eax ; Set eax to 0
mov eax, 0 ; Set eax to 0
I'm not 100% sure about, but i think the XOR is used because of some historical reason.
MrSykkox
- 528
- 4
- 14
-
-
Well, it's not always easy to see the problem if it is to easy to see ;) – MrSykkox Oct 30 '14 at 05:37
-
9XORing a register with itself to set it to zero was a fairly common optimization on 8-bit processors as it was usually a single-byte instruction. It often took less space and executed faster than an immediate load with 0 which took two bytes. – Martin James Oct 30 '14 at 08:26
-
6@MartinJames: It's still the shortest and fastest way to zero a register on x86/x86-64. It requires no immediate (->short) and is special-cased on new processors to use very few execution resources while breaking dependency chains. It's useful. – EOF Oct 30 '14 at 12:24
-
-
xor has many usages like toggling bit, parity check, checksum calculation... It isn't there for historical reasons. – phuclv Nov 01 '14 at 05:43
-
xor is used because it's shorter and CPUs recognized that as a special case of setting to 0. There are some more reasons addressed in the other duplicated questions – phuclv Nov 05 '14 at 06:35
3
xor ax, ax would do the same as mov ax, 0, but with additional capability of setting the flag to zero and clearing carry according to the logic of xor. And xor consumes less clocks than mov does in some old architectures.
mov eax,eax would take up 5 bytes in byte code where xor eax,eax would consume 2 bytes.
Rusiru Adithya Samarasinghe
- 77
- 1
- 9
-
There's already a canonical answer about why `xor`-zeroing is better: https://stackoverflow.com/questions/33666617/what-is-the-best-way-to-set-a-register-to-zero-in-x86-assembly-xor-mov-or-and. `xor` is still faster on modern Intel CPUs, even apart from code-size. It's not just a historical / old architecture thing. (On AMD CPUs, it's just a code-size advantage, but it's not slower so compilers use it.) – Peter Cordes Jan 30 '18 at 15:34