Understanding Bitwise Operators - Code

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

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<>Operator Nowthatweunderstandtheleftbitshift,thenextone,therightbitshift,willbeeasy.Everythingslidestotherighttheamountwespecify.Theonlyslightdifferenceiswhattheemptybitsgetfilledwith. Ifwe'restartingwithanegativenumber(abinarynumberwheretheleftmostbitisa1),alltheemptyspacesarefilledwitha1.Ifwe'restartingwithapositivenumber(wheretheleftmostbit,ormostsignificantbit,isa0),thenalltheemptyspacesarefilledwitha0.Again,thisallgoesbacktotwo'scomplement. Whilethissoundscomplicated,itbasicallyjustpreservesthesignofthenumberwestartwith.So-8>>2==-2while8>>2==2.I'drecommendtryingthoseoutonpaperyourself. Since>>istheoppositeof<>>Operator Ourfinalbitwiseoperatoristhebitwiseunsignedrightshift.Thisisverysimilartotheregularbitwiserightshift,exceptthatallemptybitsontheleftarefilledwith0s.Thismeanstheresultofthisoperatorisalwaysapositiveintegeranditalwaystreatstheintegerbeingshiftedasanunsignedinteger.Wewon'trunthroughanexampleofthisinthissection,butwe'llseeauseforitveryshortly. UsingBitwiseOperatorstoWorkWithColors OneofthemostpracticalusesofbitwiseoperatorsinActionscript3isworkingwithcolors,whicharestoredtypicallyasuints. Thestandardformatforcolorsistowritetheminhexadecimal:0xAARRGGBB-eachletterrepresentsahexadecimaldigit.Here,thefirsttwohexadecimaldigits,whichareequivalenttothefirsteightbinarydigits,representouralpha,ortransparency.Thenexteightbitsrepresenttheamountofredinourcolor(soanintegerfrom0to255),thenexteighttheamountofgreen,andthefinaleightrepresenttheamountofblueinourcolor. Withoutbitwiseoperators,it'sextremelydifficulttoworkwithcolorsinthisformat-butwiththemit'seasy! Challenge1:Findtheamountofblueinacolor:Usingthe&operator,trytofindtheamountofblueinanarbitrarycolor. publicfunctionfindBlueComponent(color:uint):uint { //Yourcodehere! } Weneedawayto'erase'ormaskalltheotherdataincolorandjusthavethebluecomponentleft.Thisiseasy,actually!Ifwetakecolor&0x000000FF-or,writtenmoresimply,color&0xFF-weendupwithonlythebluecomponent. Asyoucanseefromaboveandyoulearnedinthedescriptionofthe&operator,anybinarydigit&0willalwaysequal0,whileanybinarydigit&1willkeepitsvalue.Soifwemaskourcolorby0xFFwhichonlyhas1swherethebluecomponentofourcolorislocated,weendupwithjustthebluecomponent. Challenge2:Findtheamountofredinacolor:Usingtwobitwiseoperators,trytofindtheamountofredinanarbitrarycolor. publicfunctionfindRedComponent(color:uint):uint { //Yourcodehere! } Weactuallyhavetwosolutionstothisproblem.Onewouldbereturn(color&0xFF0000)>>16;andtheotherwouldbereturn(color>>16)&0xFF; ThisisverysimilartoChallenge1,exceptthatwehavetoshiftouransweratsomepoint. Challenge3:Findthetransparencyofacolor:Usingonlyonebitwiseoperator,trytofindthealphaofacolor(anintegerfrom0to255). publicfunctionfindAlphaComponent(color:uint):uint { //Yourcodehere! } Thisoneisatouchtrickier.Wehavetobecarefulwithwhichrightshiftoperaterwechoose.Becausewe'reworkingwiththeleftmostdigitsofauint,wewanttouse>>>operator.So,ouranswersimplyisreturncolor>>>24;. FinalChallenge:Createacolorfromitscomponents:Usingthe<



請為這篇文章評分?