Bitwise operation - Wikipedia

文章推薦指數: 80 %
投票人數:10人

In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral at the level of its individual bits. Bitwiseoperation FromWikipedia,thefreeencyclopedia Jumptonavigation Jumptosearch Computersciencetopic Thisarticleneedsadditionalcitationsforverification.Pleasehelpimprovethisarticlebyaddingcitationstoreliablesources.Unsourcedmaterialmaybechallengedandremoved.Findsources: "Bitwiseoperation" – news ·newspapers ·books ·scholar ·JSTOR(August2018)(Learnhowandwhentoremovethistemplatemessage) "Binaryshift"redirectshere.Fortheexcess-3code,seeShiftedbinary(code).Forthegeneralconcept,seeOffsetbinary. Incomputerprogramming,abitwiseoperationoperatesonabitstring,abitarrayorabinarynumeral(consideredasabitstring)atthelevelofitsindividualbits.Itisafastandsimpleaction,basictothehigher-levelarithmeticoperationsanddirectlysupportedbytheprocessor.Mostbitwiseoperationsarepresentedastwo-operandinstructionswheretheresultreplacesoneoftheinputoperands. Onsimplelow-costprocessors,typically,bitwiseoperationsaresubstantiallyfasterthandivision,severaltimesfasterthanmultiplication,andsometimessignificantlyfasterthanaddition.Whilemodernprocessorsusuallyperformadditionandmultiplicationjustasfastasbitwiseoperationsduetotheirlongerinstructionpipelinesandotherarchitecturaldesignchoices,bitwiseoperationsdocommonlyuselesspowerbecauseofthereduceduseofresources.[1] Contents 1Bitwiseoperators 1.1NOT 1.2AND 1.3OR 1.4XOR 1.5Mathematicalequivalents 1.6Truthtableforallbinarylogicaloperators 2Bitshifts 2.1Bitaddressing 2.2Arithmeticshift 2.3Logicalshift 2.4Circularshift 2.4.1Rotate 2.4.2Rotatethroughcarry 2.5Inhigh-levellanguages 2.5.1C-familyandPython 2.5.1.1Circularshifts 2.5.2Java 2.5.3JavaScript 2.5.4Pascal 3Other 4Applications 5Booleanalgebra 5.1AND 5.2OR 5.3NOT 5.4XOR 5.5Others 5.6Inversesandsolvingequations 5.7Orderofoperations 6Seealso 7References 8Externallinks Bitwiseoperators[edit] Intheexplanationsbelow,anyindicationofabit'spositioniscountedfromtheright(leastsignificant)side,advancingleft.Forexample,thebinaryvalue0001(decimal1)haszeroesateverypositionbutthefirst(i.e.,therightmost)one. NOT[edit] Seealso:One'scomplement ThebitwiseNOT,orbitwisecomplement,isaunaryoperationthatperformslogicalnegationoneachbit,formingtheones'complementofthegivenbinaryvalue.Bitsthatare0become1,andthosethatare1become0.Forexample: NOT0111(decimal7) =1000(decimal8) NOT10101011(decimal171) =01010100(decimal84) Theresultisequaltothetwo'scomplementofthevalueminusone.Iftwo'scomplementarithmeticisused,thenNOTx=-x−1. Forunsignedintegers,thebitwisecomplementofanumberisthe"mirrorreflection"ofthenumberacrossthehalf-waypointoftheunsignedinteger'srange.Forexample,for8-bitunsignedintegers,NOTx=255-x,whichcanbevisualizedonagraphasadownwardlinethateffectively"flips"anincreasingrangefrom0to255,toadecreasingrangefrom255to0.Asimplebutillustrativeexampleuseistoinvertagrayscaleimagewhereeachpixelisstoredasanunsignedinteger. AND[edit] BitwiseANDof4-bitintegers AbitwiseANDisabinaryoperationthattakestwoequal-lengthbinaryrepresentationsandperformsthelogicalANDoperationoneachpairofthecorrespondingbits.Thus,ifbothbitsinthecomparedpositionare1,thebitintheresultingbinaryrepresentationis1(1 ×1 =1);otherwise,theresultis0(1 ×0 =0and0 ×0 =0).Forexample: 0101(decimal5) AND0011(decimal3) =0001(decimal1) Theoperationmaybeusedtodeterminewhetheraparticularbitisset(1)orclear(0).Forexample,givenabitpattern0011(decimal3),todeterminewhetherthesecondbitissetweuseabitwiseANDwithabitpatterncontaining1onlyinthesecondbit: 0011(decimal3) AND0010(decimal2) =0010(decimal2) Becausetheresult0010isnon-zero,weknowthesecondbitintheoriginalpatternwasset.Thisisoftencalledbitmasking.(Byanalogy,theuseofmaskingtapecovers,ormasks,portionsthatshouldnotbealteredorportionsthatarenotofinterest.Inthiscase,the0valuesmaskthebitsthatarenotofinterest.) ThebitwiseANDmaybeusedtoclearselectedbits(orflags)ofaregisterinwhicheachbitrepresentsanindividualBooleanstate.ThistechniqueisanefficientwaytostoreanumberofBooleanvaluesusingaslittlememoryaspossible. Forexample,0110(decimal6)canbeconsideredasetoffourflags,wherethefirstandfourthflagsareclear(0),andthesecondandthirdflagsareset(1).ThethirdflagmaybeclearedbyusingabitwiseANDwiththepatternthathasazeroonlyinthethirdbit: 0110(decimal6) AND1011(decimal11) =0010(decimal2) Becauseofthisproperty,itbecomeseasytochecktheparityofabinarynumberbycheckingthevalueofthelowestvaluedbit.Usingtheexampleabove: 0110(decimal6) AND0001(decimal1) =0000(decimal0) Because6AND1iszero,6isdivisiblebytwoandthereforeeven. OR[edit] BitwiseORof4-bitintegers AbitwiseORisabinaryoperationthattakestwobitpatternsofequallengthandperformsthelogicalinclusiveORoperationoneachpairofcorrespondingbits.Theresultineachpositionis0ifbothbitsare0,whileotherwisetheresultis1.Forexample: 0101(decimal5) OR0011(decimal3) =0111(decimal7) ThebitwiseORmaybeusedtosetto1theselectedbitsoftheregisterdescribedabove.Forexample,thefourthbitof0010(decimal2)maybesetbyperformingabitwiseORwiththepatternwithonlythefourthbitset: 0010(decimal2) OR1000(decimal8) =1010(decimal10) XOR[edit] BitwiseXORof4-bitintegers AbitwiseXORisabinaryoperationthattakestwobitpatternsofequallengthandperformsthelogicalexclusiveORoperationoneachpairofcorrespondingbits.Theresultineachpositionis1ifonlyoneofthebitsis1,butwillbe0ifbothare0orbothare1.Inthisweperformthecomparisonoftwobits,being1ifthetwobitsaredifferent,and0iftheyarethesame.Forexample: 0101(decimal5) XOR0011(decimal3) =0110(decimal6) ThebitwiseXORmaybeusedtoinvertselectedbitsinaregister(alsocalledtoggleorflip).AnybitmaybetoggledbyXORingitwith1.Forexample,giventhebitpattern0010(decimal2)thesecondandfourthbitsmaybetoggledbyabitwiseXORwithabitpatterncontaining1inthesecondandfourthpositions: 0010(decimal2) XOR1010(decimal10) =1000(decimal8) ThistechniquemaybeusedtomanipulatebitpatternsrepresentingsetsofBooleanstates. AssemblylanguageprogrammersandoptimizingcompilerssometimesuseXORasashort-cuttosettingthevalueofaregistertozero.PerformingXORonavalueagainstitselfalwaysyieldszero,andonmanyarchitecturesthisoperationrequiresfewerclockcyclesandmemorythanloadingazerovalueandsavingittotheregister. Ifthesetofbitstringsoffixedlengthn(i.e.machinewords)isthoughtofasann-dimensionalvectorspace F 2 n {\displaystyle{\bf{F}}_{2}^{n}} overthefield F 2 {\displaystyle{\bf{F}}_{2}} ,thenvectoradditioncorrespondstothebitwiseXOR. Mathematicalequivalents[edit] Assuming x ≥ y {\displaystylex\geqy} ,forthenon-negativeintegers,thebitwiseoperationscanbewrittenasfollows: NOT ⁡ x = ∑ n = 0 ⌊ log 2 ⁡ ( x ) ⌋ 2 n [ ( ⌊ x 2 n ⌋ mod 2 + 1 ) mod 2 ] = 2 ⌊ log 2 ⁡ ( x ) ⌋ + 1 − 1 − x x AND ⁡ y = ∑ n = 0 ⌊ log 2 ⁡ ( x ) ⌋ 2 n ( ⌊ x 2 n ⌋ mod 2 ) ( ⌊ y 2 n ⌋ mod 2 ) x OR ⁡ y = ∑ n = 0 ⌊ log 2 ⁡ ( x ) ⌋ 2 n ( [ ( ⌊ x 2 n ⌋ mod 2 ) + ( ⌊ y 2 n ⌋ mod 2 ) + ( ⌊ x 2 n ⌋ mod 2 ) ( ⌊ y 2 n ⌋ mod 2 ) ] mod 2 ) x XOR ⁡ y = ∑ n = 0 ⌊ log 2 ⁡ ( x ) ⌋ 2 n ( [ ( ⌊ x 2 n ⌋ mod 2 ) + ( ⌊ y 2 n ⌋ mod 2 ) ] mod 2 ) = ∑ n = 0 ⌊ log 2 ⁡ ( x ) ⌋ 2 n [ ( ⌊ x 2 n ⌋ + ⌊ y 2 n ⌋ ) mod 2 ] {\displaystyle{\begin{aligned}\operatorname{NOT}x&=\sum_{n=0}^{\lfloor\log_{2}(x)\rfloor}2^{n}\left[\left(\left\lfloor{\frac{x}{2^{n}}}\right\rfloor{\bmod{2}}+1\right){\bmod{2}}\right]=2^{\left\lfloor\log_{2}(x)\right\rfloor+1}-1-x\\x\operatorname{AND}y&=\sum_{n=0}^{\lfloor\log_{2}(x)\rfloor}2^{n}\left(\left\lfloor{\frac{x}{2^{n}}}\right\rfloor{\bmod{2}}\right)\left(\left\lfloor{\frac{y}{2^{n}}}\right\rfloor{\bmod{2}}\right)\\x\operatorname{OR}y&=\sum_{n=0}^{\lfloor\log_{2}(x)\rfloor}2^{n}\left(\left[\left(\left\lfloor{\frac{x}{2^{n}}}\right\rfloor{\bmod{2}}\right)+\left(\left\lfloor{\frac{y}{2^{n}}}\right\rfloor{\bmod{2}}\right)+\left(\left\lfloor{\frac{x}{2^{n}}}\right\rfloor{\bmod{2}}\right)\left(\left\lfloor{\frac{y}{2^{n}}}\right\rfloor{\bmod{2}}\right)\right]{\bmod{2}}\right)\\x\operatorname{XOR}y&=\sum_{n=0}^{\lfloor\log_{2}(x)\rfloor}2^{n}\left(\left[\left(\left\lfloor{\frac{x}{2^{n}}}\right\rfloor{\bmod{2}}\right)+\left(\left\lfloor{\frac{y}{2^{n}}}\right\rfloor{\bmod{2}}\right)\right]{\bmod{2}}\right)=\sum_{n=0}^{\lfloor\log_{2}(x)\rfloor}2^{n}\left[\left(\left\lfloor{\frac{x}{2^{n}}}\right\rfloor+\left\lfloor{\frac{y}{2^{n}}}\right\rfloor\right){\bmod{2}}\right]\end{aligned}}} Truthtableforallbinarylogicaloperators[edit] Thereare16possibletruthfunctionsoftwobinaryvariables;thisdefinesatruthtable. HereisthebitwiseequivalentoperationsoftwobitsPandQ: p q F0 NOR1 Xq2 ¬p3 ↛4 ¬q5 XOR6 NAND7 AND8 XNOR9 q10 If/then11 p12 Then/if13 OR14 T15 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 0 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 Bitwiseequivalents 0 NOT(pORq) (NOTp)ANDq NOTp pAND(NOTq) NOTq pXORq NOT(pANDq) pANDq NOT(pXORq) q (NOTp)ORq p pOR(NOTq) pORq 1 Bitshifts[edit] Thebitshiftsaresometimesconsideredbitwiseoperations,becausetheytreatavalueasaseriesofbitsratherthanasanumericalquantity.Intheseoperations,thedigitsaremoved,orshifted,totheleftorright.Registersinacomputerprocessorhaveafixedwidth,sosomebitswillbe"shiftedout"oftheregisteratoneend,whilethesamenumberofbitsare"shiftedin"fromtheotherend;thedifferencesbetweenbitshiftoperatorslieinhowtheydeterminethevaluesoftheshifted-inbits. Bitaddressing[edit] Ifthewidthoftheregister(frequently32oreven64)islargerthanthenumberofbits(usually8)ofthesmallestaddressableunit,frequentlycalledbyte,theshiftoperationsinduceanaddressingschemefromthebytestothebits. Therebytheorientations"left"and"right"aretakenfromthestandardwritingofnumbersinaplace-valuenotation,suchthataleftshiftincreasesandarightshiftdecreasesthevalueofthenumber―iftheleftdigitsarereadfirst,thismakesupabig-endianorientation. Disregardingtheboundaryeffectsatbothendsoftheregister,arithmeticandlogicalshiftoperationsbehavethesame,andashiftby8 bitpositionstransportsthebitpatternby1 bytepositioninthefollowingway: Little-endianordering: aleftshiftby8positionsincreasesthebyteaddressby1, arightshiftby8positionsdecreasesthebyteaddressby1. Big-endianordering: aleftshiftby8positionsdecreasesthebyteaddressby1, arightshiftby8positionsincreasesthebyteaddressby1. Arithmeticshift[edit] Mainarticle:Arithmeticshift Leftarithmeticshift Rightarithmeticshift Inanarithmeticshift,thebitsthatareshiftedoutofeitherendarediscarded.Inaleftarithmeticshift,zerosareshiftedinontheright;inarightarithmeticshift,thesignbit(theMSBintwo'scomplement)isshiftedinontheleft,thuspreservingthesignoftheoperand. Thisexampleusesan8-bitregister,interpretedastwo'scomplement: 00010111(decimal+23)LEFT-SHIFT =00101110(decimal+46) 10010111(decimal−105)RIGHT-SHIFT =11001011(decimal−53) Inthefirstcase,theleftmostdigitwasshiftedpasttheendoftheregister,andanew0wasshiftedintotherightmostposition.Inthesecondcase,therightmost1wasshiftedout(perhapsintothecarryflag),andanew1wascopiedintotheleftmostposition,preservingthesignofthenumber.Multipleshiftsaresometimesshortenedtoasingleshiftbysomenumberofdigits.Forexample: 00010111(decimal+23)LEFT-SHIFT-BY-TWO =01011100(decimal+92) Aleftarithmeticshiftbynisequivalenttomultiplyingby2n(providedthevaluedoesnotoverflow),whilearightarithmeticshiftbynofatwo'scomplementvalueisequivalenttotakingthefloorofdivisionby2n.Ifthebinarynumberistreatedasones'complement,thenthesameright-shiftoperationresultsindivisionby2nandroundingtowardzero. Logicalshift[edit] Mainarticle:Logicalshift Leftlogicalshift Rightlogicalshift Inalogicalshift,zerosareshiftedintoreplacethediscardedbits.Therefore,thelogicalandarithmeticleft-shiftsareexactlythesame. However,asthelogicalright-shiftinsertsvalue0bitsintothemostsignificantbit,insteadofcopyingthesignbit,itisidealforunsignedbinarynumbers,whilethearithmeticright-shiftisidealforsignedtwo'scomplementbinarynumbers. Circularshift[edit] Furtherinformation:Circularshift Anotherformofshiftisthecircularshift,bitwiserotationorbitrotation. Rotate[edit] Leftcircularshiftorrotate Rightcircularshiftorrotate Inthisoperation,sometimescalledrotatenocarry,thebitsare"rotated"asiftheleftandrightendsoftheregisterwerejoined.Thevaluethatisshiftedintotherightduringaleft-shiftiswhatevervaluewasshiftedoutontheleft,andviceversaforaright-shiftoperation.Thisisusefulifitisnecessarytoretainalltheexistingbits,andisfrequentlyusedindigitalcryptography.[clarificationneeded] Rotatethroughcarry[edit] Leftrotatethroughcarry Rightrotatethroughcarry Rotatethroughcarryisavariantoftherotateoperation,wherethebitthatisshiftedin(oneitherend)istheoldvalueofthecarryflag,andthebitthatisshiftedout(ontheotherend)becomesthenewvalueofthecarryflag. Asinglerotatethroughcarrycansimulatealogicalorarithmeticshiftofonepositionbysettingupthecarryflagbeforehand.Forexample,ifthecarryflagcontains0,thenxRIGHT-ROTATE-THROUGH-CARRY-BY-ONEisalogicalright-shift,andifthecarryflagcontainsacopyofthesignbit,thenxRIGHT-ROTATE-THROUGH-CARRY-BY-ONEisanarithmeticright-shift.Forthisreason,somemicrocontrollerssuchaslowendPICsjusthaverotateandrotatethroughcarry,anddon'tbotherwitharithmeticorlogicalshiftinstructions. Rotatethroughcarryisespeciallyusefulwhenperformingshiftsonnumberslargerthantheprocessor'snativewordsize,becauseifalargenumberisstoredintworegisters,thebitthatisshiftedoffoneendofthefirstregistermustcomeinattheotherendofthesecond.Withrotate-through-carry,thatbitis"saved"inthecarryflagduringthefirstshift,readytoshiftinduringthesecondshiftwithoutanyextrapreparation. Inhigh-levellanguages[edit] Furtherinformation:Circularshift§ Implementingcircularshifts C-familyandPython[edit] InC-familylanguages,thelogicalshiftoperatorsare"<>"forrightshift.Thenumberofplacestoshiftisgivenasthesecondargumenttotheoperator.Forexample, x=y<<2; assignsxtheresultofshiftingytotheleftbytwobits,whichisequivalenttoamultiplicationbyfour. Shiftscanresultinimplementation-definedbehaviororundefinedbehavior,socaremustbetakenwhenusingthem.Theresultofshiftingbyabitcountgreaterthanorequaltotheword'ssizeisundefinedbehaviorinCandC++.[2][3]Right-shiftinganegativevalueisimplementation-definedandnotrecommendedbygoodcodingpractice;[4]theresultofleft-shiftingasignedvalueisundefinediftheresultcannotberepresentedintheresulttype.[2] InC#,theright-shiftisanarithmeticshiftwhenthefirstoperandisanintorlong.Ifthefirstoperandisoftypeuintorulong,theright-shiftisalogicalshift.[5] Circularshifts[edit] TheC-familyoflanguageslackarotateoperator(althoughC++20providesstd::rotlandstd::rotr),butonecanbesynthesizedfromtheshiftoperators.Caremustbetakentoensurethestatementiswellformedtoavoidundefinedbehaviorandtimingattacksinsoftwarewithsecurityrequirements.[6]Forexample,anaiveimplementationthatleft-rotatesa32-bitunsignedvaluexbynpositionsissimply uint32_tx=...,n=...; uint32_ty=(x<>(32-n)); However,ashiftby0bitsresultsinundefinedbehaviorintheright-handexpression(x>>(32-n))because32-0is32,and32isoutsidetherange0–31inclusive.Asecondtrymightresultin uint32_tx=...,n=...; uint32_ty=n?(x<>(32-n)):x; wheretheshiftamountistestedtoensurethatitdoesnotintroduceundefinedbehavior.However,thebranchaddsanadditionalcodepathandpresentsanopportunityfortiminganalysisandattack,whichisoftennotacceptableinhigh-integritysoftware.[6]Inaddition,thecodecompilestomultiplemachineinstructions,whichisoftenlessefficientthantheprocessor'snativeinstruction. ToavoidtheundefinedbehaviorandbranchesunderGCCandClang,thefollowingisrecommended.Thepatternisrecognizedbymanycompilers,andthecompilerwillemitasinglerotateinstruction:[7][8][9] uint32_tx=...,n=...; uint32_ty=(x<>(-n&31)); Therearealsocompiler-specificintrinsicsimplementingcircularshifts,like_rotl8,_rotl16,_rotr8,_rotr16inMicrosoftVisualC++.ClangprovidessomerotateintrinsicsforMicrosoftcompatibilitythatsufferstheproblemsabove.[9]GCCdoesnotofferrotateintrinsics.Intelalsoprovidesx86intrinsics. Java[edit] InJava,allintegertypesaresigned,sothe"<>"operatorsperformarithmeticshifts.Javaaddstheoperator">>>"toperformlogicalrightshifts,butsincethelogicalandarithmeticleft-shiftoperationsareidenticalforsignedinteger,thereisno"<<>(signedrightshift),and>>>(unsignedrightshift)arecalledtheshiftoperators. Thetypeoftheshiftexpressionisthepromotedtypeoftheleft-handoperand.Forexample,aByte>>>2isequivalentto((int)aByte)>>>2. Ifthepromotedtypeoftheleft-handoperandisint,onlythefivelowest-orderbitsoftheright-handoperandareusedastheshiftdistance.Itisasiftheright-handoperandweresubjectedtoabitwiselogicalANDoperator&withthemaskvalue0x1f(0b11111).[11]Theshiftdistanceactuallyusedisthereforealwaysintherange0to31,inclusive. Ifthepromotedtypeoftheleft-handoperandislong,thenonlythesixlowest-orderbitsoftheright-handoperandareusedastheshiftdistance.Itisasiftheright-handoperandweresubjectedtoabitwiselogicalANDoperator&withthemaskvalue0x3f(0b111111).[11]Theshiftdistanceactuallyusedisthereforealwaysintherange0to63,inclusive. Thevalueofn>>>sisnright-shiftedsbitpositionswithzero-extension. Inbitandshiftoperations,thetypebyteisimplicitlyconvertedtoint.Ifthebytevalueisnegative,thehighestbitisone,thenonesareusedtofilluptheextrabytesintheint.Sobyteb1=-5;inti=b1|0x0200;willresultini==-5. JavaScript[edit] JavaScriptusesbitwiseoperationstoevaluateeachoftwoormoreunitsplaceto1or0.[12] Pascal[edit] InPascal,aswellasinallitsdialects(suchasObjectPascalandStandardPascal),thelogicalleftandrightshiftoperatorsare"shl"and"shr",respectively.Evenforsignedintegers,shrbehaveslikealogicalshift,anddoesnotcopythesignbit.Thenumberofplacestoshiftisgivenasthesecondargument.Forexample,thefollowingassignsxtheresultofshiftingytotheleftbytwobits: x:=yshl2; Other[edit] popcount,usedincryptography countleadingzeros Applications[edit] Bitwiseoperationsarenecessaryparticularlyinlower-levelprogrammingsuchasdevicedrivers,low-levelgraphics,communicationsprotocolpacketassembly,anddecoding. Althoughmachinesoftenhaveefficientbuilt-ininstructionsforperformingarithmeticandlogicaloperations,alltheseoperationscanbeperformedbycombiningthebitwiseoperatorsandzero-testinginvariousways.[13]Forexample,hereisapseudocodeimplementationofancientEgyptianmultiplicationshowinghowtomultiplytwoarbitraryintegersaandb(agreaterthanb)usingonlybitshiftsandaddition: c←0 whileb≠0 if(band1)≠0 c←c+a leftshiftaby1 rightshiftbby1 returnc Anotherexampleisapseudocodeimplementationofaddition,showinghowtocalculateasumoftwointegersaandbusingbitwiseoperatorsandzero-testing: whilea≠0 c←banda b←bxora leftshiftcby1 a←c returnb Booleanalgebra[edit] Mainarticle:Booleanalgebra Sometimesitisusefultosimplifycomplexexpressionsmadeupofbitwiseoperations.Forexample,whenwritingcompilers.Thegoalofacompileristotranslateahighlevelprogramminglanguageintothemostefficientmachinecodepossible.Booleanalgebraisusedtosimplifycomplexbitwiseexpressions. AND[edit] x&y=y&x x&(y&z)=(x&y)&z x&0xFFFF=x[14] x&0=0 x&x=x OR[edit] x|y=y|x x|(y|z)=(x|y)|z x|0=x x|0xFFFF=0xFFFF x|x=x NOT[edit] ~(~x)=x XOR[edit] x^y=y^x x^(y^z)=(x^y)^z x^0=x x^y^y=x x^x=0 x^0xFFFF=~x Additionally,XORcanbecomposedusingthe3basicoperations(AND,OR,NOT) a^b=(a|b)&(~a|~b) a^b=(a&~b)|(~a&b) Others[edit] x|(x&y)=x x&(x|y)=x ~(x|y)=~x&~y ~(x&y)=~x|~y x|(y&z)=(x|y)&(x|z) x&(y|z)=(x&y)|(x&z) x&(y^z)=(x&y)^(x&z) x+y=(x^y)+((x&y)<<1) x-y=~(~x+y) Inversesandsolvingequations[edit] Itcanbehardtosolveforvariablesinbooleanalgebra,becauseunlikeregularalgebra,severaloperationsdonothaveinverses.Operationswithoutinverseslosesomeoftheoriginaldatabitswhentheyareperformed,anditisnotpossibletorecoverthismissinginformation. Hasinverse NOT XOR Rotateleft Rotateright Noinverse AND OR Shiftleft Shiftright Orderofoperations[edit] Mainarticle:OperatorsinCandC++§ Operatorprecedence Operationsatthetopofthislistareexecutedfirst.Seethemainarticleforamorecompletelist. () ~-[15] */ % +-[16] <<>> & ^ | Seealso[edit] Arithmeticlogicunit Bitmanipulation Bitboard BitwiseoperationsinC Booleanalgebra(logic) Doubledabble Findfirstset Karnaughmap Logicgate Logicaloperator Primitivedatatype References[edit] ^"CMicrotekLow-powerDesignBlog".CMicrotek.Retrieved2015-08-12. ^abJTC1/SC22/WG14N843"Cprogramminglanguage",section6.5.7 ^"Arithmeticoperators-cppreference.com".en.cppreference.com.Retrieved2016-07-06. ^"INT13-C.Usebitwiseoperatorsonlyonunsignedoperands".CERT:SecureCodingStandards.SoftwareEngineeringInstitute,CarnegieMellonUniversity.Retrieved2015-09-07. ^"Operator(C#Reference)".Microsoft.Retrieved2013-07-14. ^ab"Nearconstanttimerotatethatdoesnotviolatethestandards?".StackExchangeNetwork.Retrieved2015-08-12. ^"Pooroptimizationofportablerotateidiom".GNUGCCProject.Retrieved2015-08-11. ^"CircularrotatethatdoesnotviolateC/C++standard?".IntelDeveloperForums.Retrieved2015-08-12. ^ab"Constantnotpropagatedintoinlineassembly,resultsin"constraint'I'expectsanintegerconstantexpression"".LLVMProject.Retrieved2015-08-11. ^TheJavaLanguageSpecification,section15.19.ShiftOperators ^ab"Chapter15.Expressions".oracle.com. ^"JavaScriptBitwise".W3Schools.com. ^"Synthesizingarithmeticoperationsusingbit-shiftingtricks".Bisqwit.iki.fi.2014-02-15.Retrieved2014-03-08. ^Throughoutthisarticle,0xFFFFmeansthatallthebitsinyourdatatypeneedtobesetto1.Theexactnumberofbitsdependsonthewidthofthedatatype. ^-isnegationhere,notsubtraction ^-issubtractionhere,notnegation Externallinks[edit] OnlineBitwiseCalculatorsupportsBitwiseAND,ORandXOR XORcat,atoolforbitwise-XORfiles/streams Divisionusingbitshifts "BitwiseOperationsModN"byEnriqueZeleny,WolframDemonstrationsProject. "PlotsOfCompositionsOfBitwiseOperations"byEnriqueZeleny,TheWolframDemonstrationsProject. Retrievedfrom"https://en.wikipedia.org/w/index.php?title=Bitwise_operation&oldid=1096740546" Categories:BinaryarithmeticOperators(programming)BooleanalgebraHiddencategories:ArticleswithshortdescriptionShortdescriptionisdifferentfromWikidataArticlesneedingadditionalreferencesfromAugust2018AllarticlesneedingadditionalreferencesUsedmydatesfromAugust2018WikipediaarticlesneedingclarificationfromAugust2020Articleswithexamplepseudocode Navigationmenu Personaltools NotloggedinTalkContributionsCreateaccountLogin Namespaces ArticleTalk English Views ReadEditViewhistory More Search Navigation MainpageContentsCurrenteventsRandomarticleAboutWikipediaContactusDonate Contribute HelpLearntoeditCommunityportalRecentchangesUploadfile Tools WhatlinkshereRelatedchangesUploadfileSpecialpagesPermanentlinkPageinformationCitethispageWikidataitem Print/export DownloadasPDFPrintableversion Languages БългарскиCatalàČeštinaDeutschEspañolEsperantoفارسیFrançais한국어हिन्दीItalianoעבריתLatviešuLombardMagyarMirandés日本語PolskiPortuguêsРусскийSimpleEnglishSuomiSvenskaУкраїнськаTiếngViệt粵語中文 Editlinks



請為這篇文章評分?