Bitwise operation - Wikipedia
文章推薦指數: 80 %
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<
延伸文章資訊
- 1Bitwise Operators in C: AND, OR, XOR, Shift & Complement - Guru99
- 2你所不知道的C 語言:bitwise 操作 - HackMD
延伸閱讀: Bitwise Operators in C (連結失效). Uses of Bitwise Operations or Why to Study Bits. Compression...
- 3Bitwise operation - Wikipedia
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary nu...
- 4Bitwise Operators in C | GATE Notes - Byju's
- 5Bitwise Operators in C/C++ - GeeksforGeeks
The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numb...