Assembly Language for Beginners

(nextflipdebug2) #1

2.6 XOR (exclusive OR)


2.6 XOR (exclusive OR)


XORis widely used when one needs just to flip specific bit(s). Indeed, theXORoperation applied with 1
effectively inverts a bit:


input A input B output
0 0 0
0 1 1
1 0 1
1 1 0

And vice-versa, theXORoperation applied with 0 does nothing, i.e., it’s an idle operation. This is a very
important property of theXORoperation and it’s highly recommended to memorize it.


2.6.1 Everyday speech.


XORoperationpresentincommoneverydayspeech. Whensomeoneasks“pleasebuyapplesorbananas”,
thisusuallymeans“buythefirstobjectorthesecond, butnotboth”—thisisexactlyexclusiveOR,because
logical OR would mean “both objects are also fine”.


Some people suggest “and/or” should be used in everyday speech to make emphasis that logical OR is
used instead of exclusive OR:https://en.wikipedia.org/wiki/And/or.


2.6.2 Encryption.


XOR is heavily used in both amateur (9.1) andrealencryption (at least inFeistel network).


XOR is very useful here because:cipher_text=plain_text⊕keyand then:(plain_text⊕key)⊕key=plain_text.


2.6.3 RAID 4


RAID4 offers a very simple method to protect hard disks. For example, there are several disks (D 1 ,D 2 ,D 3 ,
etc.) and one parity disk (P). Each bit/byte written to parity disk is calculated and written on-fly:


P=D 1 ⊕D 2 ⊕D 3 (2.1)

If any of disks is failed, for example,D 2 , it’s restored using the very same way:


D 2 =D 1 ⊕P⊕D 3 (2.2)

If parity disk failed, it is restored using2.1way. If two of any disks are failed, then it wouldn’t be possible
to restore both.


RAID5 is more advanced, but this XOR property is still exploited there.


That’s whyRAIDcontrollers has hardware “XOR accelerators” helping to XOR large chunks of written data
on-fly. When computers get faster and faster, it now can be done at software level, usingSIMD.


2.6.4 XOR swap algorithm


Hard to believe, but this code swaps values inEAXandEBXwithout aid of any other additional register or
memory cell:


xor eax, ebx
xor ebx, eax
xor eax, ebx


Let’s find out, how it works. First, we will rewrite it to step aside from x86 assembly language:

Free download pdf