I\'m getting into assembly and I keep running into xor, for example:
xor ax, ax
Does it just clear the register\'s value?
xor ax,ax is used to set ax to 0.
Reason: typically xor instruction on any processor takes less bytes in assembling, than using movl 0,%ax
In this case it will clear the register... XOR is an "exclusive or"... so if ax contains 1010 and you exclusive or that with 1010 you'll get 0000 (cleared)
xor ax, ax
is the fastest possible way to set the ax register to 0
. Fastest in terms of the size of instruction and number of instructions. For detail about how it works you need a little knowledge of bit arithmetic.
XOR operation between two bits returns 1 if one and only one of the two bits is 1; 0 otherwise. Another way to explain is that that it returns 1 if the two bits are different; 0 otherwise.
XOR operation between two binary numbers of same length works likewise on a bit-by-bit basis. XOR two numbers you get a number with bits set to 1 where corresponding bits of the two operands differ, 0 when corresponding bits are same.
From this knowledge its fairly easy to see that if the two operands are the same (ax and ax for example) the result will be 0.
A XOR B
in english would be translated as "are A and B not equal". So xor ax, ax
will set ax
to zero since ax is always equal to itself.
A B | A XOR B
0 0 | 0
1 0 | 1
0 1 | 1
1 1 | 0
A B | XOR
0 0 | 0
1 0 | 1
0 1 | 1
1 1 | 0
The XOR instruction does the above operation on every pair of bits in the two operands. So 0xFF xor 0xFF
would be 0x00
and 0x55 xor 0xAA
would be 0xFF
. And yes, xor ax ax
clears ax
.
When I started programming a long time ago there was no exclusive or on either the processor or in the compiler. When I got around to it I stuck to the descriptions:
so:
0 or 0 = 0
0 or 1 = 1
1 or 0 = 1
1 or 1 = 1
and
0 xor 0 = 0
0 xor 1 = 1
1 xor 0 = 1
1 xor 1 = 0