Sie sind auf Seite 1von 4

11/2/2016 TheMagicofXOR

TheMagicofXOR
Introduction

Inmathematics,inclusiveORisgivenpreferencetoexclusiveOR(alsocalledXOR).

Forexample,whenyouwritepVqwhichisread"pORq",thisisinclusiveOR.Thisstatementistruewhen
pistrue,orqistrue,orbothpandqistrue.InclusiveORisusedasthedefaultmeaningofOR,andworks
moreofteninlogicthanexclusiveOR.

WeoftenseeXORusedinsentences.Forexample,ifsomeonesays"Thissummer,IamgoingtoLondon,or
IamgoingtoParis",theyseemtosuggestthattheyplantogotooneortheother,butnotboth.Eventhough
theirstatementwouldn'tbeconsideredwrongiftheywenttobothcities,itsuggestsverystronglythatthey
intendtogotoonecity.(Ofcourse,inlogic,it'shardtoconveythenotion"suggestsverystrongly").

YouwouldthinkXORwouldn'tbethatinterestinganoperator.It'ssimilartoOR,sowhyshoulditbeany
moreinterestingthanOR?

Butitis!

VariousViewsofXOR

YoucanthinkofXORinmanyways.AssumethatpandqareBooleanvariables.Alsoassumethatp1,p2,
...pnareBooleanvariables.Let(+)betheXORoperator(thisisacirclewithaplussigninsideit).Inthis
case,weassumethatpandqarebooleanvalues,insteadofwords,andweassume(+)isplainXOR,not
bitwiseXOR.Lateron,we'lluseitasbitwiseXOR.

p(+)qistrueifexactlyoneofpandqistrue.ThisistheconventionaldefinitionofXOR.
p1(+)p2(+)...(+)pnistrueifthenumberofvariableswiththevaluetrueisodd(andisfalseifthe
numberofvariableswiththevaluetrueiseven).Noticethisdefinitionignoresthevariableswhichare
assignedtofalse.

ThismayseemlikeanoddviewofXOR.(Nopunintended).However,ifyoubelievethatXORis
associative(whichitis),it'smerelyanextensionofthefirstdefinitionofXOR.

Thisdefinitionmakessense,ifyoureadthenextdefinition.

p1(+)p2(+)...(+)pnisthesameasaddingmodulo2.Ifpiistrue,thentreatitasa1,otherwisetreat
itasa0.Then,XORoperationisequivalentto:

p1(+)p2(+)...(+)pn==(p1+p2+...+pn)%2

Thus,XORappliedtoabunchofBooleanvariablesisthesameassummingupallthevariables'values
(wheretrueis1andfalseis0),anddividingmod2.Recallthatdividingmod2isonewayto
determineifanumberisevenorodd.Sinceonlythevariablesthathavevalue1contributetothesum
(0istheidentityvalueinsums),thisdetermineshowmanyvariableshavevalue1.

ParityCheck

PeopleoftenuseXORasameansofdoingaparitycheck.Abitstringhasevenparityifthenumberof1'sin
thestringiseven.Ithasanoddparityifthenumberof1'sisodd.IfyouXORthebitstogether,youcantell
whetherabitstringhasevenoroddparity.

Thiscanoftenbeusedtoverifydatasentacrossanetwork,wherethere'ssomeprobabilityabitmaybe
corrupted.Forexample,supposeyou'resendingNbytesacrossthenetworkfromasourcelocationtoa
https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/xor.html 1/4
11/2/2016 TheMagicofXOR

destinationlocation.

Howcanyoudeterminewhetherthebytesweresentcorrectly?Onewayistouseakindofchecksum,which
usesXOR.Eachbytecanbewrittenasb7b6...b0.Foreachbyte,XORallthebitsinpositionbi.

IfNwas10,andyou'retransmitting10bytes,thencreatean11thbytewherebiistheXORofall10bytesith
bit.This11thbyteiscalledthechecksum.Thischecksumisalsosentacrossthenetwork.

Atthedestinationend,wherethedataisbeingreceived,youcanthenindependentlyperformthechecksum
again,andseeifthechecksumyouperformedmatchesthechecksumsentacross.Ifso,thenyouhavesome
confidencethatnobyteswerecorrupted.Ifit'snotthesame,thenthenetworkhascorruptedsomebytes,and
youmayneedtoretransmitthedata.

Clearlythesystemcouldhaveerrors.Forexample,iftwobitswereflipped,say,bit3ofbytes4and5,then
thechecksumwouldbethesameiftheyhadn'tbeenflipped,buttherewouldstillbeerrors.Nevertheless,it
catchessomeerrors.

PropertiesofXOR
HereareseveralusefulpropertiesofXOR.ThisappliestoplainXORandbitwiseXOR.

x(+)0=x

XORingwith0givesyoubackthesamenumber.Thus,0istheidentityforXOR.

x(+)1=\x

XORingwith1givesyoubackthenegationofthebit.Again,thiscomesfromthetruthtable.For
bitwiseXOR,thepropertyisslightlydifferent:x^~0=~x.Thatis,ifyouXORwithall1's,theresult
willbethebitwisenegationofx.

x(+)x=0

XORingxwithitselfgivesyou0.That'sbecausexiseither0or1,and0(+)0=0and1(+)1=0.

XORisassociative.

Thatis:(x(+)y)(+)z=x(+)(y(+)z).

Youcanverifythisbyusingtruthtables.

XORiscommutative.

Thatis:x(+)y=y(+)x.

Youcanverifythisbyusingtruthtables.

BitwiseXOR

ThepropertiesofXORapplytobitwiseXOR.Supposexandyare32bitwords.Then,x^yisbasicallylike
performing32XORsinparallelonanarrayof32booleans.

Swappingwithout"temp"
Here'soneofthosebrainteasersthatyoucangivetoyourCSfriends.OneoftheclassicproblemsanyCS
majorshouldbeabletosolveiswritingcodetoswaptwonumbers.Here'showitlooksinC.

https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/xor.html 2/4
11/2/2016 TheMagicofXOR

temp=x;
x=y;
y=temp;
Toswap,youintroducea"temp"variable.Itsnamedoesn'thavetobe"temp",butitisneverthelessan
additionaltemporaryvariable.

Nowaskyourfriendtosolvethiswithoutusingatempvariable.ThismeansyoucanONLYusexandy.
ThisdoesNOTmeanthatyounamethevariabletemp2.

Howcanyoudothis?Ifyou'rethinking"perhapsIcanusebitwiseXOR",you'reright!Ifyou're
adventuresome,youcanthinkabouthowtodothisonyourown,butifnot,here'stheanswer.

x=x^y;
y=x^y;
x=x^y;
Areyouconvincedthisworks?Perhapsnot.Howcouldyoubeconvincedthisworks?

Thekeytoconvincingyourselfthisworksistokeeptrackoftheoriginalvalueofxandy.LetAbethe
originalvalueofx(thatis,thevaluexhasjustbeforerunningthesethreelinesofcode).Similarly,letBbe
theoriginalvalueofy.

Wecancommenteachlineofcodetoseewhat'shappening.

//x==A,y==B
x=x^y;
//x==A^B,y==B
y=x^y;
//x==A^B
//y==(A^B)^B==A^(B^B)(byAssoc)
//==A^0(byz^z==0property)
//==A(byz^0==zproperty)
x=x^y;
//x==(A^B)^A
//==(A^A)^B(byAssoc/Commutativity)
//==0^B(byz^z==0property)
//==B(byz^0==zproperty)
//y==A
Afterthesecondstatementhasexecuted,y=A.Afterthethirdstatement,x=B.

NowitturnsoutyoucandoasimilartrickusingsubtractioninsteadofXOR.DoingswapswithXORis
slightlysaferthanswappingwithsubtractionbecausesubtractioncancauseoverflow.However,usually
overflowoccursina"niceway"thatitmaystillwork.Overflowoftenjust"wrapsaround",sothingsmay
stillworkoutfine.

WritingbitwiseXORwithout^
SupposeyouwantedtoimplementbitwiseXOR,butdidn'thave^operator.Whatwouldyoudo?With
bitwiseAND(&)andbitwiseOR(|),youcandothis.

x^y==(~x&y)|(x&~y)
https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/xor.html 3/4
11/2/2016 TheMagicofXOR

ThisisthestandarddefinitionofXORasdefinedinlogicbooks,appliedtobitwiseoperations.

Summary
XORisaninterestingoperation.Withit,youcandoparitychecksandswapswithouttempvariables.

https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/xor.html 4/4

Das könnte Ihnen auch gefallen