Bitwise Operators in C/C++ - GeeksforGeeks

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

The | (bitwise OR) in C or C++ takes two numbers as operands and does OR on every bit of two numbers. The result of OR is 1 if any of the two ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage ArrayMatrixStringsHashingLinkedListStackQueueBinaryTreeBinarySearchTreeHeapGraphSearchingSortingDivide&ConquerMathematicalGeometricBitwiseGreedyBacktrackingBranchandBoundDynamicProgrammingPatternSearchingRandomized CompleteInterviewPreparationat20%off|Usecode:PREPAREKAROCheckNow RelatedArticles ▲RelatedArticlesBitwiseAlgorithmsBitwiseOperatorsinC/C++PythonBitwiseOperatorsBitsmanipulation(Importanttactics)LittleandBigEndianMysterySmallestofthreeintegerswithoutcomparisonoperatorsFindthetwonon-repeatingelementsinanarrayofrepeatingelements/UniqueNumbers2WriteanEfficientCProgramtoReverseBitsofaNumberSmallestpowerof2greaterthanorequaltonHowtoswaptwobitsinagiveninteger?CopysetbitsinarangeGraytoBinaryandBinarytoGrayconversionKaratsubaalgorithmforfastmultiplicationusingDivideandConqueralgorithmComputetheparityofanumberusingXORandtablelook-upBooth’sMultiplicationAlgorithmFindthen-thnumberwhosebinaryrepresentationisapalindromeOptimizationTechniques|Set1(Modulus)BitFieldsinCWhatarethedifferencesbetweenbitwiseandlogicalANDoperatorsinC/C++?C++bitsetanditsapplicationC++bitsetinterestingfactsBuiltinfunctionsofGCCcompilerBitwiseAlgorithmsBitwiseOperatorsinC/C++PythonBitwiseOperatorsBitsmanipulation(Importanttactics)LittleandBigEndianMysterySmallestofthreeintegerswithoutcomparisonoperatorsFindthetwonon-repeatingelementsinanarrayofrepeatingelements/UniqueNumbers2WriteanEfficientCProgramtoReverseBitsofaNumberSmallestpowerof2greaterthanorequaltonHowtoswaptwobitsinagiveninteger?CopysetbitsinarangeGraytoBinaryandBinarytoGrayconversionKaratsubaalgorithmforfastmultiplicationusingDivideandConqueralgorithmComputetheparityofanumberusingXORandtablelook-upBooth’sMultiplicationAlgorithmFindthen-thnumberwhosebinaryrepresentationisapalindromeOptimizationTechniques|Set1(Modulus)BitFieldsinCWhatarethedifferencesbetweenbitwiseandlogicalANDoperatorsinC/C++?C++bitsetanditsapplicationC++bitsetinterestingfactsBuiltinfunctionsofGCCcompilerBitwiseOperatorsinC/C++ViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: MediumLastUpdated: 27May,2022InC,thefollowing6operatorsarebitwiseoperators(workatbit-level)  The&(bitwiseAND)inCorC++takestwonumbersasoperandsanddoesANDoneverybitoftwonumbers.TheresultofANDis1onlyifbothbitsare1.  The|(bitwiseOR)inCorC++takestwonumbersasoperandsanddoesORoneverybitoftwonumbers.TheresultofORis1ifanyofthetwobitsis1. The^(bitwiseXOR)inCorC++takestwonumbersasoperandsanddoesXORoneverybitoftwonumbers.TheresultofXORis1ifthetwobitsaredifferent. The<>(rightshift)inCorC++takestwonumbers,rightshiftsthebitsofthefirstoperand,thesecondoperanddecidesthenumberofplacestoshift. The~(bitwiseNOT)inCorC++takesonenumberandinvertsallbitsofit.  Example: C++#includeusingnamespacestd; intmain(){      //a=5(00000101),b=9(00001001)    inta=5,b=9;     //Theresultis00000001    cout<>1"<>1)<intmain(){    //a=5(00000101),b=9(00001001)    unsignedchara=5,b=9;     //Theresultis00000001    printf("a=%d,b=%d\n",a,b);    printf("a&b=%d\n",a&b);     //Theresultis00001101    printf("a|b=%d\n",a|b);     //Theresultis00001100    printf("a^b=%d\n",a^b);     //Theresultis11111010    printf("~a=%d\n",a=~a);     //Theresultis00010010    printf("b<<1=%d\n",b<<1);     //Theresultis00000100    printf("b>>1=%d\n",b>>1);     return0;   }Outputa=5,b=9 a&b=1 a|b=13 a^b=12 ~a=-6 b<<1=18 b>>1=4InterestingfactsaboutbitwiseoperatorsTheleftshiftandrightshiftoperatorsshouldnotbeusedfornegativenumbers.Ifthesecondoperand(whichdecidesthenumberofshifts)isanegativenumber,itresultsinundefinedbehaviourinC.Forexampleresultsofboth1<>-1isundefined.Also,ifthenumberisshiftedmorethanthesizeoftheinteger,thebehaviourisundefined.Forexample,1<<33isundefinedifintegersarestoredusing32bits.Anotherthingis,NOshiftoperationisperformedifadditive-expression(operandthatdecidesnoofshifts)is0.Seethisformoredetails. Note:InC++,thisbehavioriswell-defined.Interestingly!!ThebitwiseORoftwonumbersisjustthesumofthosetwonumbersifthereisnocarryinvolved,otherwiseyoujustaddtheirbitwiseAND.Let’ssay,wehavea=5(101)andb=2(010),sincethereisnocarryinvolved,theirsumisjusta|b.Now,ifwechange‘a’to6whichis110inbinary,theirsumwouldchangetoa|b+a&bsincethereisacarryinvolved. ThebitwiseXORoperatoristhemostusefuloperatorfromatechnicalinterviewperspective.Itisusedinmanyproblems.Asimpleexamplecouldbe“Givenasetofnumberswhereallelementsoccuranevennumberoftimesexceptonenumber,findtheoddoccurringnumber”ThisproblemcanbeefficientlysolvedbyjustdoingXORtoallnumbers.  C++#includeusingnamespacestd; //Functiontoreturntheonlyodd//occurringelementintfindOdd(intarr[],intn){    intres=0,i;    for(i=0;i //Functiontoreturntheonlyodd//occurringelementintfindOdd(intarr[],intn){    intres=0,i;    for(i=0;iusingnamespacestd; intmain(){    intx=2,y=5;    (x&y)?cout< intmain(){    intx=2,y=5;    (x&y)?printf("True"):printf("False");    (x&&y)?printf("True"):printf("False");    return0;}OutputFalseTrueTheleft-shiftandright-shiftoperatorsareequivalenttomultiplicationanddivisionby2respectively.Asmentionedinpoint1,itworksonlyifnumbersarepositive.  C++#includeusingnamespacestd; intmain(){     intx=19;    cout<>1="<>1)< intmain(){    intx=19;    printf("x<<1=%d\n",x<<1);    printf("x>>1=%d\n",x>>1);    return0;}Outputx<<1=38 x>>1=9The&operatorcanbeusedtoquicklycheckifanumberisoddoreven.Thevalueofexpression(x&1)wouldbenon-zeroonlyifxisodd,otherwisethevaluewouldbezero.  C++#includeusingnamespacestd; intmain(){     intx=19;    (x&1)?cout< intmain(){    intx=19;    (x&1)?printf("Odd"):printf("Even");    return0;}OutputOddThe~operatorshouldbeusedcarefully.Theresultof~operatoronasmallnumbercanbeabignumberiftheresultisstoredinanunsignedvariable.Andtheresultmaybeanegativenumberiftheresultisstoredinasignedvariable(assumingthatthenegativenumbersarestoredin2’scomplementformwheretheleftmostbitisthesignbit) C++#includeusingnamespacestd; intmain(){     unsignedintx=1;    signedinta=1;    cout< intmain(){    unsignedintx=1;    printf("SignedResult%d\n",~x);    printf("UnsignedResult%ud\n",~x);    return0;}OutputSignedResult-2 UnsignedResult4294967294Bitsmanipulation(Importanttactics)BitwiseHacksforCompetitiveProgrammingBitTricksforCompetitiveProgramming  MyPersonalNotes arrow_drop_upSave LikeNext PythonBitwiseOperatorsRecommendedArticlesPage:07,May1902,Dec2022,Feb2128,Jul1529,Jul1523,Dec1215,Dec1308,Mar1528,Feb2007,Aug2005,Nov2010,Mar1430,Jan1830,Nov1701,Jun1731,May1701,Apr1812,Nov1817,Sep2029,Oct2004,Oct2012,Oct2031,May2109,Nov20ArticleContributedBy:GeeksforGeeksVotefordifficultyCurrentdifficulty: MediumEasy Normal Medium Hard ExpertImprovedBy:ShubhamDhiman1prakash_AmanRaj1608VijaySingh8shireenfatima12mayunitpshivanisinghss2110sathiyamoorthics19harendrakumar123yaraalsham86mitalibhola94shromworldArticleTags:Bitwise-XORC-Operatorscpp-operatorBitMagicCLanguageC++PracticeTags:cpp-operatorBitMagicCPPReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinBitMagicLeftShiftandRightShiftOperatorsinC/C++CountsetbitsinanintegerTravellingSalesmanProblem|Set1(NaiveandDynamicProgramming)Howtoswaptwonumberswithoutusingatemporaryvariable?Programtofindwhetheragivennumberispowerof2MostvisitedinCLanguagestd::sort()inC++STLArraysinC/C++DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()SubstringinC++MultidimensionalArraysinC/C++ImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?