Bitwise Operator in C - javatpoint

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

Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits ... ⇧SCROLLTOTOP Home C C++ C# Java SQL HTML CSS JavaScript XML Ajax Android Cloud DesignPattern Quiz Projects InterviewQ Comment Forum CTutorial WhatisCLanguage HistoryofC FeaturesofC HowtoinstallC FirstCProgram CompilationProcessinC printfscanf VariablesinC DataTypesinc Keywordsinc CIdentifiers COperators CComments CFormatSpecifier CEscapeSequence ASCIIvalueinC ConstantsinC LiteralsinC TokensinC CBoolean StaticinC ProgrammingErrorsinC CompiletimevsRuntime ConditionalOperatorinC BitwiseOperatorinC 2scomplementinC CFundamentalTest CControlStatements Cif-else Cswitch if-elsevsswitch CLoops Cdo-whileloop Cwhileloop Cforloop NestedLoopsinC InfiniteLoopinC Cbreak Ccontinue Cgoto TypeCasting CControlStatementTest CFunctions Whatisfunction Call:Value&Reference Recursioninc StorageClasses CFunctionsTest CArray 1-DArray 2-DArray ReturnanArrayinC ArraytoFunction CArrayTest CPointers CPointers CPointertoPointer CPointerArithmetic DanglingPointersinC sizeof()operatorinC constPointerinC voidpointerinC CDereferencePointer NullPointerinC CFunctionPointer FunctionpointerasargumentinC CPointersTest CDynamicMemory Dynamicmemory CStrings StringinC Cgets()&puts() CStringFunctions Cstrlen() Cstrcpy() Cstrcat() Cstrcmp() Cstrrev() Cstrlwr() Cstrupr() Cstrstr() CStringTest CMath CMathFunctions CStructureUnion CStructure typedefinC CArrayofStructures CNestedStructure StructurePaddinginC CUnion CStructureTest CFileHandling CFileHandling Cfprintf()fscanf() Cfputc()fgetc() Cfputs()fgets() Cfseek() Crewind() Cftell() CPreprocessor CPreprocessor CMacros C#include C#define C#undef C#ifdef C#ifndef C#if C#else C#error C#pragma CPreprocessorTest CCommandLine CommandLineArguments CMisc CExpressions DataSegments FlowofCProgram ClassificationofProgrammingLanguages EnuminC Whatisgetch()inC WhatisthefunctioncallinC typedefvsdefineinC CProgrammingTest CProgrammingTest CPrograms Top10+CPrograms FibonacciSeries PrimeNumber PalindromeNumber Cprogramtocomparethetwostrings StringsConcatenationinC Factorial ArmstrongNumber Sumofdigits CountthenumberofdigitsinC ReverseNumber SwapNumber Print"Hello"without; AssemblycodeinC Cprogramwithoutmain MatrixMultiplication DecimaltoBinary NumberinCharacters AlphabetTriangle NumberTriangle FibonacciTriangle HexadecimaltoBinary HexadecimaltoDecimal OctaltoHexadecimalinC StrongnumberinC StarPrograminC itoaFunctioninC ExtraLongFactorialsinC LeapyearprograminC PerfectNumberPrograminC VariablesvsConstants RoundRobinPrograminCwithOutput CProgramtofindtherootsofquadraticequation TypeCastingvsTypeConversion HowtorunaCprograminVisualStudioCode ModulusOperatorinC/C++ SumoffirstNnaturalnumbersinC BigONotationinC LCMoftwonumbersinC whileloopvsdo-whileloopinC MemoryLayoutinC BalancedParenthesisinC BinarytoDecimalNumberinC GCDoftwonumbersinC Getchar()functioninC flowchartinC SimpsonMethod PyramidPatternsinC RandomFunctioninC Floyd'sTriangleinC CHeaderFiles abs()functioninC Atoi()functioninC StructurePointerinC sprintf()inC RangeofIntinC CProgramtoconvert24Hourtimeto12Hourtime WhatisdoubleinC WhatisthemaininC CalculatorPrograminC CallocinC user-definedvslibraryfunctioninC MemsetC ASCIITableinC StaticfunctioninC ReverseaStringinC TwinPrimeNumbersinC strchr()functioninC StructureofaCprogram PowerFunctioninC MallocinC TablePrograminC TypesofRecursioninC ConvertUppercasetoLowercaseinC UnaryOperatorinC ArithmeticOperatorinC CeilFunctioninC RelationalOperatorinC AssignmentOperatorinC Pre-incrementandPost-incrementOperatorinC PointervsarrayinC RestrictkeywordinC Theexit()functioninC ConstQualifierinC SequencePointsinC AnagraminC IncrementandDecrementOperatorsinC LogicalANDOperatorinC ShiftOperatorsinC Near,Far,andHugepointersinClanguage MagicNumberinC RemoveDuplicateElementsfromanArrayinC GenericLinkedlistinC isalnum()functioninC isalpha()functioninC BisectionMethodinC snprintf()functioninC RemoveanelementfromanarrayinC SquareRootinC isprint()functioninC isdigit()functioninC isgraph()functioninC LogicalNOT(!)OperatorinC Self-referentialstructure BreakVs.ContinueinC Forvs.WhileloopinC MCQ ClanguageMCQ ClanguageMCQPart2 Math PrimeNumbersList CompositeNumbersList SquareNumbersList BinaryNumbersList FibonacciNumbersList OuncesinaCup OuncesinaPound OuncesinaGallon OuncesinaLiter OuncesinaPint OuncesinaQuart OuncesinaTablespoon CInterview CInterviewQuestions next→ ←prev BitwiseOperatorinC Thebitwiseoperatorsaretheoperatorsusedtoperformtheoperationsonthedataatthebit-level.Whenweperformthebitwiseoperations,thenitisalsoknownasbit-levelprogramming.Itconsistsoftwodigits,either0or1.Itismainlyusedinnumericalcomputationstomakethecalculationsfaster. WehavedifferenttypesofbitwiseoperatorsintheCprogramminglanguage.Thefollowingisthelistofthebitwiseoperators: Operator Meaningofoperator & BitwiseANDoperator | BitwiseORoperator ^ BitwiseexclusiveORoperator ~ One'scomplementoperator(unaryoperator) << Leftshiftoperator >> Rightshiftoperator Let'slookatthetruthtableofthebitwiseoperators. 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 1 BitwiseANDoperator BitwiseANDoperatorisdenotedbythesingleampersandsign(&).Twointegeroperandsarewrittenonbothsidesofthe(&)operator.Ifthecorrespondingbitsofboththeoperandsare1,thentheoutputofthebitwiseANDoperationis1;otherwise,theoutputwouldbe0. Forexample, Wehavetwovariablesaandb. a=6; b=4; Thebinaryrepresentationoftheabovetwovariablesaregivenbelow: a=0110 b=0100 WhenweapplythebitwiseANDoperationintheabovetwovariables,i.e.,a&b,theoutputwouldbe: Result=0100 Aswecanobservefromtheaboveresultthatbitsofboththevariablesarecomparedonebyone.Ifthebitofboththevariablesis1thentheoutputwouldbe1,otherwise0. Let'sunderstandthebitwiseANDoperatorthroughtheprogram. #include intmain() { inta=6,b=14;//variabledeclarations printf("TheoutputoftheBitwiseANDoperatora&bis%d",a&b); return0; } Intheabovecode,wehavecreatedtwovariables,i.e.,'a'and'b'.Thevaluesof'a'and'b'are6and14respectively.Thebinaryvalueof'a'and 'b'are0110and1110,respectively.WhenweapplytheANDoperatorbetweenthesetwovariables, aANDb=0110&&1110=0110 Output BitwiseORoperator ThebitwiseORoperatorisrepresentedbyasingleverticalsign(|).Twointegeroperandsarewrittenonbothsidesofthe(|)symbol.Ifthebitvalueofanyoftheoperandis1,thentheoutputwouldbe1,otherwise0. Forexample, Weconsidertwovariables, a=23; b=10; Thebinaryrepresentationoftheabovetwovariableswouldbe: a=00010111 b=00001010 WhenweapplythebitwiseORoperatorintheabovetwovariables,i.e.,a|b,thentheoutputwouldbe: Result=00011111 Aswecanobservefromtheaboveresultthatthebitsofboththeoperandsarecomparedonebyone;ifthevalueofeitherbitis1,thentheoutputwouldbe1otherwise0. Let'sunderstandthebitwiseORoperatorthroughaprogram. #include intmain() { inta=23,b=10;//variabledeclarations printf("TheoutputoftheBitwiseORoperatora|bis%d",a|b); return0; } Output BitwiseexclusiveORoperator BitwiseexclusiveORoperatorisdenotedby(^)symbol.TwooperandsarewrittenonbothsidesoftheexclusiveORoperator.Ifthecorrespondingbitofanyoftheoperandis1thentheoutputwouldbe1,otherwise0. Forexample, Weconsidertwovariablesaandb, a=12; b=10; Thebinaryrepresentationoftheabovetwovariableswouldbe: a=00001100 b=00001010 WhenweapplythebitwiseexclusiveORoperatorintheabovetwovariables(a^b),thentheresultwouldbe: Result=00001110 Aswecanobservefromtheaboveresultthatthebitsofboththeoperandsarecomparedonebyone;ifthecorrespondingbitvalueofanyoftheoperandis1,thentheoutputwouldbe1otherwise0. Let'sunderstandthebitwiseexclusiveORoperatorthroughaprogram. #include intmain() { inta=12,b=10;//variabledeclarations printf("TheoutputoftheBitwiseexclusiveORoperatora^bis%d",a^b); return0; } Output Bitwisecomplementoperator Thebitwisecomplementoperatorisalsoknownasone'scomplementoperator.Itisrepresentedbythesymboltilde(~).Ittakesonlyoneoperandorvariableandperformscomplementoperationonanoperand.Whenweapplythecomplementoperationonanybits,then0becomes1and1becomes0. Forexample, Ifwehaveavariablenamed'a', a=8; Thebinaryrepresentationoftheabovevariableisgivenbelow: a=1000 Whenweapplythebitwisecomplementoperatortotheoperand,thentheoutputwouldbe: Result=0111 Aswecanobservefromtheaboveresultthatifthebitis1,thenitgetschangedto0else1. Let'sunderstandthecomplementoperatorthroughaprogram. #include intmain() { inta=8;//variabledeclarations printf("TheoutputoftheBitwisecomplementoperator~ais%d",~a); return0; } Output Bitwiseshiftoperators TwotypesofbitwiseshiftoperatorsexistinCprogramming.Thebitwiseshiftoperatorswillshiftthebitseitherontheleft-sideorright-side.Therefore,wecansaythatthebitwiseshiftoperatorisdividedintotwocategories: Left-shiftoperator Right-shiftoperator Left-shiftoperator Itisanoperatorthatshiftsthenumberofbitstotheleft-side. Syntaxoftheleft-shiftoperatorisgivenbelow: Operand< intmain() { inta=5;//variableinitialization printf("Thevalueofa<<2is:%d",a<<2); return0; } Output Right-shiftoperator Itisanoperatorthatshiftsthenumberofbitstotherightside. Syntaxoftheright-shiftoperatorisgivenbelow: Operand>>n; Where, Operandisanintegerexpressiononwhichweapplytheright-shiftoperation. Nisthenumberofbitstobeshifted. Inthecaseoftheright-shiftoperator,'n'bitswillbeshiftedontheright-side.The'n'bitsontheright-sidewillbepoppedout,and'n'bitsontheleft-sidearefilledwith0. Forexample, Supposewehaveastatement, inta=7; Thebinaryrepresentationoftheabovevariablewouldbe: a=0111 Ifwewanttoright-shifttheaboverepresentationby2,thenthestatementwouldbe: a>>2; 00000111>>2=00000001 Let'sunderstandthroughaprogram. #include intmain() { inta=7;//variableinitialization printf("Thevalueofa>>2is:%d",a>>2); return0; } Output NextTopic2scomplementinC ←prev next→ ForVideosJoinOurYoutubeChannel:JoinNow Feedback SendyourFeedbackto[email protected] HelpOthers,PleaseShare LearnLatestTutorials Splunk SPSS Swagger Transact-SQL Tumblr ReactJS Regex ReinforcementLearning RProgramming RxJS ReactNative PythonDesignPatterns PythonPillow PythonTurtle Keras Preparation Aptitude Reasoning VerbalAbility InterviewQuestions CompanyQuestions TrendingTechnologies ArtificialIntelligence AWS Selenium CloudComputing Hadoop ReactJS DataScience Angular7 Blockchain Git MachineLearning DevOps B.Tech/MCA DBMS DataStructures DAA OperatingSystem ComputerNetwork CompilerDesign ComputerOrganization DiscreteMathematics EthicalHacking ComputerGraphics SoftwareEngineering WebTechnology CyberSecurity Automata CProgramming C++ Java .Net Python Programs ControlSystem DataMining DataWarehouse JavatpointServicesJavaTpointofferstoomanyhighqualityservices.Mailuson[email protected],togetmoreinformationaboutgivenservices.WebsiteDesigningWebsiteDevelopmentJavaDevelopmentPHPDevelopmentWordPressGraphicDesigningLogoDigitalMarketingOnPageandOffPageSEOPPCContentDevelopmentCorporateTrainingClassroomandOnlineTrainingDataEntryTrainingForCollegeCampusJavaTpointofferscollegecampustrainingonCoreJava,AdvanceJava,.Net,Android,Hadoop,PHP,WebTechnologyandPython.Pleasemailyourrequirementat[email protected]Duration:1weekto2weekLike/Subscribeusforlatestupdatesornewsletter



請為這篇文章評分?