Understanding Bitwise Operators - Code
文章推薦指數: 80 %
Bitwise operators are operators (just like +, *, &&, etc.) that operate on ints and uints at the binary level. This means they look directly at ...
7days
ofWordPressplugins,themes&templates-forfree!*
Unlimitedassetdownloads!
Start7-DayFreeTrial
DismissSignInHow-ToTutorialsDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGameDevelopmentComputerSkillsCoursesDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGuidesDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGameDevelopmentComputerSkillsEnvatoElementsEnvatoStudioCommunityHelpEnvatoElementsEnvatoStudioCommunityForumHelpSignInHow-ToTutorialsDesign&IllustrationAdobePhotoshopAdobeIllustratorDrawingAdobeInDesignPhotoManipulationGraphicDesignTextEffectsVectorPhotoshopActionsIconDesignMoreCategories...LearningGuidesCodeJavaScriptWordPressMobileDevelopmentPHPLaravelCMSSwiftAndroidSDKReactAngular2+MoreCategories...LearningGuidesWebDesignCSSHTML&CSSAnimationUIDesignAdobePhotoshopSketchWorkflowDesignTheoryJavaScriptUXMoreCategories...LearningGuidesPhoto&VideoPhotographyVideoEditingHow-ToInspirationLightingAdobePhotoshopAdobeAfterEffectsAdobePremiereProAdobeLightroomMoreCategories...LearningGuidesBusinessSmallBusinessEntrepreneurshipFreelanceCareersMarketingFinanceProductivityPlanningCommunicationHow-ToMoreCategories...LearningGuidesMusic&AudioAudioProductionLogicProGeneralMixing&MasteringSoundDesignWorkshopsReasonRecordingAbletonLiveCubaseMoreCategories...LearningGuides3D&MotionGraphicsAdobeAfterEffects3D3DStudioMaxMotionGraphicsMayaCinema4DWorkflowBlenderVisualEffectsRoundupsMoreCategories...LearningGuidesGameDevelopmentGameDesignPlatformAgnosticGameMechanicsBusinessProgrammingGameArtLevelDesignFromScratchUnityHTML5MoreCategories...LearningGuidesComputerSkillsOSXAppTrainingProductivityHow-ToTips&ShortcutsCustomizationAutomationSecurityHardwareMicrosoftPowerpointMoreCategories...LearningGuidesCoursesDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGuidesDesign&IllustrationCodeWebDesignPhoto&VideoBusinessMusic&Audio3D&MotionGraphicsGameDevelopmentComputerSkillsAdvertisementCodeExplanatoryUnderstandingBitwiseOperatorsAdvertisementAdvertisementAdvertisementAdvertisementAdvertisement
JasonKillian
Apr18,2012
10
likes
ReadTime:
16mins
Deutsch
English
Español
BahasaIndonesia
Pусский
ExplanatoryFlash
Bitwiseoperatorsarethosestrangelookingoperatorsthatmaylookhardtounderstand...butnotanymore!Thiseasytofollowarticlewillhelpyouunderstandwhattheyareandhowtousethem,withacoupleofpracticalexamplesaswelltoshowyouwhenandwhyyou'dneedthem.
Introduction
Bitwiseoperatorsareoperators(justlike+,*,&&,etc.)thatoperateonintsanduintsatthebinarylevel.Thismeanstheylookdirectlyatthebinarydigitsorbitsofaninteger.Thisallsoundsscary,butintruthbitwiseoperatorsarequiteeasytouseandalsoquiteuseful!
Itisimportant,though,thatyouhaveanunderstandingofbinarynumbersandhexadecimalnumbers.Ifyoudon't,pleasecheckoutthisarticle-itwillreallyhelpyou!Belowisalittleapplicationthatwillletyoutryoutthedifferentbitwiseoperators.
Don'tworryifyoudon'tunderstandwhatisgoingonyet,itwillallbeclearsoon...
RecognizingtheBitwiseOperators
Let'stakealookatthebitwiseoperatorsthatAS3supplies.Manyotherlanguagesarequitesimilar(forexample,JavaScriptandJavahavepracticallyidenticaloperators):
&(bitwiseAND)
|(bitwiseOR)
~(bitwiseNOT)
^(bitwiseXOR)
<>(bitwiserightshift)
>>>(bitwiseunsignedrightshift)
&=(bitwiseANDassignment)
|=(bitwiseORassignment)
^=(bitwiseXORassignment)
<<=(bitwiseleftshiftandassignment)
>>=(bitwiserightshiftandassignment)
>>>=(bitwiseunsignedrightshiftandassignment)
Thereareacoupleofthingsyoushouldtakefromthis:First,somebitwiseoperatorslooksimilartooperatorsyou'veusedbefore(&vs.&&,|vs.||).Thisisbecausetheyaresomewhatsimilar.
Second,mostbitwiseoperatorscomewithacompoundassignmentformofthemselves.Thisisthesameashowyoucanuse+and+=,-and-=,etc.
The&Operator
Upfirst:thebitwiseANDoperator,&.Aquickheads-upthough:normally,intsanduintstakeup4bytesor32bitsofspace.Thismeanseachintoruintisstoredas32binarydigits.Forthesakeofthistutorial,we'llpretendsometimesthatintsanduintsonlytakeup1byteandonlyhave8binarydigits.
The&operatorcompareseachbinarydigitoftwointegersandreturnsanewinteger,witha1whereverbothnumbershada1anda0anywhereelse.Adiagramisworthathousandwords,sohere'sonetoclearthingsup.Itrepresentsdoing37&23,whichequals5.
Noticehoweachbinarydigitof37and23arecompared,andtheresulthasa1whereverboth37and23hada1,andtheresulthasa0otherwise.
Acommonwayofthinkingaboutbinarydigitsisastrueorfalse.Thatis,1isequivalenttotrueand0isequivalenttofalse.Thismakesthe&operatormakemoresense.
Whenwecomparetwobooleans,wenormallydoboolean1&&boolean2.Thatexpressionisonlytrueifbothboolean1andboolean2aretrue.Inthesameway,integer1&integer2isequivalent,asthe&operatoronlyoutputsa1whenbothbinarydigitsofourtwointegersare1.
Here'satablethatrepresentsthatidea:
Aneatlittleuseofthe&operatoristocheckwhetheranumberisevenorodd.Forintegerswecansimplychecktherightmostbit(alsocalledtheleastsignificantbit)todetermineiftheintegerisoddoreven.Thisisbecausewhenconvertingtobase10,therightmostbitrepresents20or1.Whentherightmostbitis1,weknowthatournumberisoddsincewe'readding1toabunchofpowersoftwowhichwillalwaysbeeven.Whentherightmostbitis0,weknowournumberwillbeeven,sinceitsimplyconsistsofaddingupabunchofevennumbers.
Here'sanexample:
varrandInt:int=int(Math.random()*1000);
if(randInt&1)
{
trace("Oddnumber.");
}
else
{
trace("Evennumber.");
}
Onmycomputer,thismethodwasabout66%fasterthanusingrandInt%2tocheckforevenandoddnumbers.That'squiteaperformanceboost!
The|Operator
UpnextisthebitwiseORoperator,|.Asyoumayhaveguessed,the|operatoristothe||operatorasthe&operatoristothe&&operator.The|operatorcompareseachbinarydigitacrosstwointegersandgivesbacka1ifeitherofthemare1.Again,thisissimilartothe||operatorwithbooleans.
Let'stakealookatthesameexampleasbefore,exceptnowusingthe|operatorinsteadofthe&operator.We'renowdoing37|23whichequals55:
Flags:AUseofthe&and|Operators
Wecantakeadvantageofthe&and|operatorstoallowustopassmultipleoptionstoafunctioninasingleint.
Let'stakealookatapossiblesituation.We'rebuildingapop-upwindowclass.Atthebottomofit,wecanhaveaYes,No,Okay,orCancelbuttonoranycombinationofthose-howshouldwedothis?Here'sthehardway:
publicclassPopupWindowextendsSprite
{
//Variables,Constructor,etc...
publicstaticvoidshowPopup(yesButton:Boolean,noButton:Boolean,okayButton:Boolean,cancelButton:Boolean)
{
if(yesButton)
{
//addYESbutton
}
if(noButton)
{
//addNOButton
}
//andsoonfortherestofthebuttons
}
}
Isthishorrible?No.Butitisbad,ifyou'reaprogrammer,tohavetolookuptheorderofargumentseverytimeyoucallthefunction.It'salsoannoying-forexample,ifyouonlywanttoshowtheCancelbutton,youhavetosetalltheotherBooleanstofalse.
Let'susewhatwelearnedabout&and|tomakeabettersolution:
publicclassPopupWindowextendsSprite
{
publicstaticconstYES:int=1;
publicstaticconstNO:int=2;
publicstaticconstOKAY:int=4;
publicstaticconstCANCEL:int=8;
publicstaticvoidshowPopup(buttons:int)
{
if(buttons&YES)
{
//addYESbutton
}
if(buttons&NO)
{
//addNObutton
}
}
}
HowwouldaprogrammercallthefunctionsotheYesbutton,Nobutton,andCancelbuttonareshowing?Likethis:
PopupWindow.show(PopupWindow.YES|PopupWindow.NO|PopupWindow.CANCEL);
What'sgoingon?It'simportanttonotethatourconstantsinthesecondexampleareallpowersoftwo.So,ifwelookattheirbinaryforms,wewillnoticetheyallhaveonedigitequalto1,andtherestequalto0.Infact,theyeachhaveadifferentdigitequalto1.Thismeansthatnomatterhowwecombinethemwith|,everycombinationwillgiveusauniquenumber.Lookingatitinadifferentway,outresultofour|statementwillbeabinarynumberwitha1whereverouroptionshada1.
ForourcurrentexamplewehavePopupWindow.YES|PopupWindow.NO|PopupWindow.CANCELwhichisequivalentto1|2|8whichrewritteninbinaryis00000001|00000010|00001000whichgivesusaresultof00001011.
Now,inourshowPopup()function,weuse&tocheckwhichoptionswerepassedin.Forexample,whenwecheckbuttons&YES,allthebitsinYESareequalto0excepttheveryrightmostone.So,weareessentiallycheckingiftherightmostbitinbuttonsisa1ornot.Ifitis,buttons&YESwillnotequal0andanythingintheifstatementwillbeexecuted.Conversely,iftherightmostbitinbuttonsis0,buttons&YESwillequal0,andtheifstatementwillnotbeexecuted.
The~Operator
ThebitwiseNOToperatorisslightlydifferentthanthetwowe'velookedatsofar.Insteadoftakinganintegeroneachsideofit,ittakesanintegeronlyafterit.Thisisjustlikethe!operator,and,notsurprisingly,itdoesasimilarthing.Infact,justas!flipsabooleanfromtruetofalseorviceversa,the~operatorreverseseachbinarydigitinaninteger:from0to1and1to0:
Aquickexample.Saywehavetheinteger37,or00100101.~37isthen11011010.What'sthebase10valueofthis?Well...
Two'sComplement,uintvs.int,andMore!
Nowthefunbegins!We'regoingtotakeacloserlookatbinarynumbersonacomputer.Let'sstartwiththeuint.Asmentionedbefore,auintistypically4bytesor32bitslong,meaningithas32binarydigits.Thisiseasytounderstand:togetthebase10valuewesimplyconvertthenumbertobase10regularly.We'llalwaysgetapositivenumber.
Buthowabouttheint?Italsouses32bits,buthowdoesitstorenegativenumbers?Ifyouguessedthatthefirstdigitisusedtostorethesign,you'reontherightpath.Let'stakealookatthetwo'scomplementsystemforstoringbinarynumbers.Whilewewon'tgointoallthedetailshere,atwo'scomplementsystemisusedbecauseitmakesbinaryarithmeticeasy.
Tofindthetwo'scomplementofabinarynumber,wesimplyflipallthebits(i.e.dowhatthe~operatordoes)andaddonetotheresult.Let'strythisoutonce:
Wethendefineourresultasthevalue-37.Whydothiscomplicatedprocessandnotjustfliptheveryfirstbitandcallthat-37?
Well,let'stakeasimpleexpression37+-37.Weallknowthisshouldequal0,andwhenweaddthe37toitstwo'scomplement,that'swhatweget:
Noticethatsinceourintegersonlyholdeightbinarydigits,the1inourresultisdropped,andweendupwith0,asweshould.
Torecap,tofindthenegativeofanumber,wesimplytakeitstwo'scomplement.Wecandothisbyinvertingallthebitsandaddingone.
Wanttotrythisyourself?Addtrace(~37+1);toanAS3file,thencompileandrunit.You'llsee-37isprinted,asitshouldbe.
Thereisalsoalittleshortcuttodothisbyhand:startingfromtheright,worktotheleftuntilyoureacha1.Flipallthebitstotheleftofthisfirst1.
Whenwe'relookingatasignedbinarynumber(inotherwords,onethatcanbenegative,anintnotauint),wecanlookattheleftmostdigittotellwhetherit'snegativeorpositive.Ifit'sa0,thenthenumberispositiveandwecanconverttobase10simplybycalculatingitsbase10value.Iftheleftmostbitisa1,thenthenumberisnegative,sowetakethetwo'scomplementofthenumbertogetitspositivevalueandthensimplyaddanegativesign.
Forexample,ifwehave11110010,weknowitisanegativenumber.Wecanfindit'stwo'scomplementbyflippingallthedigitstotheleftoftherightmost1,givingus00001110.Thisequals13,soweknow11110010equals-13.
The^Operator
We'rebacktothebitwiseoperators,andupnextisthebitwiseXORoperator.Thereisnoequivalentbooleanoperatortothisone.
The^operatorissimilartothe&and|operatorsinthatittakesanintoruintonbothsides.Whenitiscalculatingtheresultingnumber,itagaincomparesthebinarydigitsofthesenumbers.Ifoneortheotherisa1,itwillinserta1intotheresult,otherwiseitwillinserta0.ThisiswherethenameXOR,or"exclusiveor"comesfrom.
Let'stakealookatourusualexample:
The^operatordoeshaveuses-it'sespeciallygoodfortogglingbinarydigits-butwewon'tcoveranypracticalapplicationsinthisarticle.
The<
延伸文章資訊
- 1你所不知道的C 語言:bitwise 操作 - HackMD
延伸閱讀: Bitwise Operators in C (連結失效). Uses of Bitwise Operations or Why to Study Bits. Compression...
- 2[ C 文章收集] Bitwise Operation - 程式扎記
接下來要介紹位元運算的一些用途. Bitwise operator 介紹: * << SHIFT LEFT , >> ...
- 3Bitwise 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...
- 4What is bitwise? - Definition from WhatIs.com - TechTarget
- 5Bitwise Operators in C [With Coding Example] | upGrad blog