Bitwise Operators in C: AND, OR, XOR, Shift & Complement

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

Bitwise operators are special operator set provided by 'C.' · They are used in bit level programming. · These operators are used to manipulate ... Skiptocontent WhatareBitwiseOperators? BitwiseOperatorsareusedformanipulatingdataatthebitlevel,alsocalledbitlevelprogramming.Bitwiseoperatesononeormorebitpatternsorbinarynumeralsattheleveloftheirindividualbits.Theyareusedinnumericalcomputationstomakethecalculationprocessfaster. Followingisthelistofbitwiseoperatorsprovidedby‘C’programminglanguage: Operator Meaning & BitwiseANDoperator | BitwiseORoperator ^ BitwiseexclusiveORoperator ~ BinaryOne’sComplementOperatorisaunaryoperator << Leftshiftoperator >> Rightshiftoperator Bitwiseoperatorscannotbedirectlyappliedtoprimitivedatatypessuchasfloat,double,etc.Alwaysrememberonethingthatbitwiseoperatorsaremostlyusedwiththeintegerdatatypebecauseofitscompatibility. Thebitwiselogicaloperatorsworkonthedatabitbybit,startingfromtheleastsignificantbit,i.e.LSBbitwhichistherightmostbit,workingtowardstheMSB(MostSignificantBit)whichistheleftmostbit. Theresultofthecomputationofbitwiselogicaloperatorsisshowninthetablegivenbelow. x y x&y x|y x^y 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 Inthistutorial,youwilllearn- WhatareBitwiseOperators? BitwiseAND BitwiseOR BitwiseExclusiveOR Bitwiseshiftoperators Bitwisecomplementoperator BitwiseAND Thisisoneofthemostcommonlyusedlogicalbitwiseoperators.Itisrepresentedbyasingleampersandsign(&).Twointegerexpressionsarewrittenoneachsideofthe(&)operator. TheresultofthebitwiseANDoperationis1ifboththebitshavethevalueas1;otherwise,theresultisalways0. Letusconsiderthatwehave2variablesop1andop2withvaluesasfollows: Op1=00001101 Op2=00011001 TheresultoftheANDoperationonvariablesop1andop2willbe Result=00001001 Aswecansee,twovariablesarecomparedbitbybit.Wheneverthevalueofabitinboththevariablesis1,thentheresultwillbe1orelse0. BitwiseOR Itisrepresentedbyasingleverticalbarsign(|).Twointegerexpressionsarewrittenoneachsideofthe(|)operator. TheresultofthebitwiseORoperationis1ifatleastoneoftheexpressionhasthevalueas1;otherwise,theresultisalways0. Letusconsiderthatwehave2variablesop1andop2withvaluesasfollows: Op1=00001101 Op2=00011001 TheresultoftheORoperationonvariablesop1andop2willbe Result=00011101 Aswecansee,twovariablesarecomparedbitbybit.Wheneverthevalueofabitinoneofthevariablesis1,thentheresultwillbe1orelse0. BitwiseExclusiveOR Itisrepresentedbyasymbol(^).Twointegerexpressionsarewrittenoneachsideofthe(^)operator. TheresultofthebitwiseExclusive-ORoperationis1ifonlyoneoftheexpressionhasthevalueas1;otherwise,theresultisalways0. Letusconsiderthatwehave2variablesop1andop2withvaluesasfollows: Op1=00001101 Op2=00011001 TheresultoftheXORoperationonvariablesop1andop2willbe Result=00010100 Aswecansee,twovariablesarecomparedbitbybit.Wheneveronlyonevariableholdsthevalue1thentheresultis0else0willbetheresult. Letuswriteasimpleprogramthatdemonstratesbitwiselogicaloperators. #include intmain() { inta=20; /*20=010100*/ intb=21; /*21=010101*/ intc=0; c=a&b;/*20=010100*/ printf("AND-Valueofcis%d\n",c); c=a|b;/*21=010101*/ printf("OR-Valueofcis%d\n",c); c=a^b;/*1=0001*/ printf("Exclusive-OR-Valueofcis%d\n",c); getch(); } Output: AND-Valueofcis20 OR-Valueofcis21 Exclusive-OR-Valueofcis1 Bitwiseshiftoperators Thebitwiseshiftoperatorsareusedtomove/shiftthebitpatternseithertotheleftorrightside.Leftandrightaretwoshiftoperatorsprovidedby‘C’whicharerepresentedasfollows: Operand<>n(RightShift) Here, anoperandisanintegerexpressiononwhichwehavetoperformtheshiftoperation. ‘n’isthetotalnumberofbitpositionsthatwehavetoshiftintheintegerexpression. Theleftshiftoperationwillshiftthe‘n’numberofbitstotheleftside.Theleftmostbitsintheexpressionwillbepoppedout,andnbitswiththevalue0willbefilledontherightside. Therightshiftoperationwillshiftthe‘n’numberofbitstotherightside.Therightmost‘n’bitsintheexpressionwillbepoppedout,andthevalue0willbefilledontheleftside. Example:xisanintegerexpressionwithdata1111.Afterperformingshiftoperationtheresultwillbe: x<<2(leftshift)=1111<<2=1100 x>>2(rightshift)=1111>>2=0011 Shiftsoperatorscanbecombinedthenitcanbeusedtoextractthedatafromtheintegerexpression.Letuswriteaprogramtodemonstratetheuseofbitwiseshiftoperators. #include intmain(){ inta=20; /*20=010100*/ intc=0; c=a<<2; /*80=101000*/ printf("Leftshift-Valueofcis%d\n",c); c=a>>2; /*05=000101*/ printf("Rightshift-Valueofcis%d\n",c); return0; } Output: Leftshift-Valueofcis80 Rightshift-Valueofcis5 Afterperformingtheleftshiftoperationthevaluewillbecome80whosebinaryequivalentis101000. Afterperformingtherightshiftoperation,thevaluewillbecome5whosebinaryequivalentis000101. Bitwisecomplementoperator Thebitwisecomplementisalsocalledasone’scomplementoperatorsinceitalwaystakesonlyonevalueoranoperand.Itisaunaryoperator. Whenweperformcomplementonanybits,allthe1’sbecome0’sandviceversa. Ifwehaveanintegerexpressionthatcontains00001111thenafterperformingbitwisecomplementoperationthevaluewillbecome11110000. Bitwisecomplementoperatorisdenotedbysymboltilde(~). Letuswriteaprogramthatdemonstratestheimplementationofbitwisecomplementoperator. #include intmain(){ inta=10; /*10=1010*/ intc=0; c=~(a); printf("Complement-Valueofcis%d\n",c); return0; } Output: Complement-Valueofcis-11 Hereisanotherprogram,withanexampleofalltheoperatoesdiscussedsofar: #include main(){ unsignedintx=48; /*48=00110000*/ unsignedinty=13; /*13=00001101*/ intz=0; z=x&y;/*0=00000000*/ printf("BitwiseANDOperator-x&y=%d\n",z); z=x|y;/*61=00111101*/ printf("BitwiseOROperator-x|y=%d\n",z); z=x^y;/*61=00111101*/ printf("BitwiseXOROperator-x^y=%d\n",z); z=~x;/*-49=11001111*/ printf("BitwiseOne'sComplementOperator-~x=%d\n",z); z=x<<2;/*192=11000000*/ printf("BitwiseLeftShiftOperatorx<<2=%d\n",z); z=x>>2;/*12=00001100*/ printf("BitwiseRightShiftOperatorx>>2=%d\n",z);} Afterwecompileandruntheprogram,itproducesthefollowingresult: BitwiseANDOperator-x&y=0 BitwiseOROperator-x|y=61 BitwiseXOROperator-x^y=61 BitwiseOne'sComplementOperator-~x=-49 BitwiseLeftShiftOperatorx<<2=192 BitwiseRightShiftOperatorx>>2=12 Summary Bitwiseoperatorsarespecialoperatorsetprovidedby‘C.’ Theyareusedinbitlevelprogramming. Theseoperatorsareusedtomanipulatebitsofanintegerexpression. Logical,shiftandcomplementarethreetypesofbitwiseoperators. Bitwisecomplementoperatorisusedtoreversethebitsofanexpression. YouMightLike: HowtoDownloadandInstallGCCCompilerinCforWindowsPC switch…caseinC(SwitchStatementinC)withExamples StringsinC:HowtoDeclare&InitializeaStringVariablesinC DifferenceBetweenCandJava|CVs.Java CVariable,Datatypes,Constants Postnavigation ReportaBug Previous PrevNextContinue Scrolltotop ToggleMenuClose Searchfor: Search



請為這篇文章評分?