In the C programming language, operations can be performed on a bit level using bitwise operators. Bitwise operations are contrasted by byte-level ...
BitwiseoperationsinC
FromWikipedia,thefreeencyclopedia
Jumptonavigation
Jumptosearch
Operationstransformingindividualbitsofintegraldatatypes
IntheCprogramminglanguage,operationscanbeperformedonabitlevelusingbitwiseoperators.
Bitwiseoperationsarecontrastedbybyte-leveloperationswhichcharacterizethebitwiseoperators'logicalcounterparts,theAND,OR,NOToperators.Insteadofperformingonindividualbits,byte-leveloperatorsperformonstringsofeightbits(knownasbytes)atatime.Thereasonforthisisthatabyteisnormallythesmallestunitofaddressablememory(i.e.datawithauniquememoryaddress).
Thisappliestobitwiseoperatorsaswell,whichmeansthateventhoughtheyoperateononlyonebitatatimetheycannotacceptanythingsmallerthanabyteastheirinput.
AlloftheseoperatorsarealsoavailableinC++,andmanyC-familylanguages.
Contents
1Bitwiseoperators
1.1BitwiseAND&
1.2BitwiseOR|
1.3BitwiseXOR^
2Shiftoperators
2.1Rightshift>>
2.1.1Rightshiftoperatorusage
2.2Leftshift<<
3Example:asimpleadditionprogram
4Bitwiseassignmentoperators
5Logicalequivalents
6Seealso
7References
8Externallinks
Bitwiseoperators[edit]
Cprovidessixoperatorsforbitmanipulation.[1]
Symbol
Operator
&
bitwiseAND
|
bitwiseinclusiveOR
^
bitwiseXOR(exclusiveOR)
<<
leftshift
>>
rightshift
~
bitwiseNOT(one'scomplement)(unary)
BitwiseAND&[edit]
bita
bitb
a&b(aANDb)
0
0
0
0
1
0
1
0
0
1
1
1
ThebitwiseANDoperatorisasingleampersand:&.ItisjustarepresentationofANDwhichdoesitsworkonthebitsoftheoperandsratherthanthetruthvalueoftheoperands.BitwisebinaryANDperformslogicalconjunction(showninthetableabove)ofthebitsineachpositionofanumberinitsbinaryform.
Forinstance,workingwithabyte(thechartype):
11001000
&10111000
--------
=10001000
Themostsignificantbitofthefirstnumberis1andthatofthesecondnumberisalso1sothemostsignificantbitoftheresultis1;inthesecondmostsignificantbit,thebitofsecondnumberiszero,sowehavetheresultas0.
[2]
BitwiseOR|[edit]
bita
bitb
a|b(aORb)
0
0
0
0
1
1
1
0
1
1
1
1
SimilartobitwiseAND,bitwiseORperformslogicaldisjunctionatthebitlevel.Itsresultisa1ifeitherofthebitsis1andzeroonlywhenbothbitsare0.Itssymbolis|whichcanbecalledapipe.
11001000
|10111000
--------
=11111000
[2]
BitwiseXOR^[edit]
bita
bitb
a^b(aXORb)
0
0
0
0
1
1
1
0
1
1
1
0
ThebitwiseXOR(exclusiveor)performsanexclusivedisjunction,whichisequivalenttoaddingtwobitsanddiscardingthecarry.Theresultiszeroonlywhenwehavetwozeroesortwoones.[3]XORcanbeusedtotogglethebitsbetween1and0.Thusi=i^1whenusedinalooptogglesitsvaluesbetween1and0.[4]
11001000
^10111000
--------
=01110000
Shiftoperators[edit]
Therearetwobitwiseshiftoperators.Theyare
Rightshift(>>)
Leftshift(<>[edit]
Thesymbolofrightshiftoperatoris>>.Foritsoperation,itrequirestwooperands.Itshiftseachbitinitsleftoperandtotheright.
Thenumberfollowingtheoperatordecidesthenumberofplacesthebitsareshifted(i.e.therightoperand).
Thusbydoingch>>3allthebitswillbeshiftedtotherightbythreeplacesandsoon.
However,donotethatashiftoperandvaluewhichiseitheranegativenumberorisgreaterthanorequaltothetotalnumberofbitsinthisvalueresultsinundefinedbehavior.Forexample,whenshiftinga32bitunsignedinteger,ashiftamountof32orhigherwouldbeundefined.
Example:
Ifthevariablechcontainsthebitpattern11100101,thench>>1willproducetheresult01110010,andch>>2willproduce00111001.
Hereblankspacesaregeneratedsimultaneouslyontheleftwhenthebitsareshiftedtotheright.Whenperformedonanunsignedtypeoranon-negativevalueinasignedtype,theoperationperformedisalogicalshift,causingtheblankstobefilledby0s(zeros).Whenperformedonanegativevalueinasignedtype,theresultistechnicallyimplementation-defined(compilerdependent),[5]howevermostcompilerswillperformanarithmeticshift,causingtheblanktobefilledwiththesetsignbitoftheleftoperand.
Rightshiftcanbeusedtodivideabitpatternby2asshown:
i=14;//Bitpattern00001110
j=i>>1;//herewehavethebitpatternshiftedby1thusweget00000111=7whichis14/2
Rightshiftoperatorusage[edit]
TypicalusageofarightshiftoperatorinCcanbeseenfromthefollowingcode.
Example:
#include
voidshowbits(unsignedintx)
{
inti=0;
for(i=(sizeof(int)*8)-1;i>=0;i--)
{
putchar(x&(1u<>m;
printf("%drightshift%dgives",j,m);
showbits(n);
}
return0;
}
Theoutputoftheaboveprogramwillbe
5225inbinary00000000000000000001010001101001
5225rightshift0gives00000000000000000001010001101001
5225rightshift1gives00000000000000000000101000110100
5225rightshift2gives00000000000000000000010100011010
5225rightshift3gives00000000000000000000001010001101
5225rightshift4gives00000000000000000000000101000110
5225rightshift5gives00000000000000000000000010100011
Leftshift<
intmain(void)
{
unsignedintx=3,y=1,sum,carry;
sum=x^y;//xXORy
carry=x&y;//xANDy
while(carry!=0)
{
carry=carry<<1;//leftshiftthecarry
x=sum;//initializexassum
y=carry;//initializeyascarry
sum=x^y;//sumiscalculated
carry=x&y;/*carryiscalculated,theloopconditionis
evaluatedandtheprocessisrepeateduntil
carryisequalto0.
*/
}
printf("%u\n",sum);//theprogramwillprint4
return0;
}
Bitwiseassignmentoperators[edit]
Cprovidesacompoundassignmentoperatorforeachbinaryarithmeticandbitwiseoperation.Eachoperatoracceptsaleftoperandandarightoperand,performstheappropriatebinaryoperationonbothandstorestheresultintheleftoperand.[6]
Thebitwiseassignmentoperatorsareasfollows.
Symbol
Operator
&=
bitwiseANDassignment
|=
bitwiseinclusiveORassignment
^=
bitwiseexclusiveORassignment
<<=
leftshiftassignment
>>=
rightshiftassignment
Logicalequivalents[edit]
Fourofthebitwiseoperatorshaveequivalentlogicaloperators.Theyareequivalentinthattheyhavethesametruthtables.However,logicaloperatorstreateachoperandashavingonlyonevalue,eithertrueorfalse,ratherthantreatingeachbitofanoperandasanindependentvalue.Logicaloperatorsconsiderzerofalseandanynonzerovaluetrue.Anotherdifferenceisthatlogicaloperatorsperformshort-circuitevaluation.
Thetablebelowmatchesequivalentoperatorsandshowsaandbasoperandsoftheoperators.
Bitwise
Logical
a&b
a&&b
a|b
a||b
a^b
a !=b
~a
!a
!=hasthesametruthtableas^butunlikethetruelogicaloperators,byitself!=isnotstrictlyspeakingalogicaloperator.Thisisbecausealogicaloperatormusttreatanynonzerovaluethesame.Tobeusedasalogicaloperator!=requiresthatoperandsbenormalizedfirst.Alogicalnotappliedtobothoperandswon’tchangethetruthtablethatresultsbutwillensureallnonzerovaluesareconvertedtothesamevaluebeforecomparison.Thisworksbecause!onazeroalwaysresultsinaoneand!onanynonzerovaluealwaysresultsinazero.
Example:
/*Equivalentbitwiseandlogicaloperatortests*/
#include
voidtestOperator(char*name,unsignedcharwas,unsignedcharexpected);
intmain(void)
{
//--Bitwiseoperators--//
//Truthtablespackedinbits
constunsignedcharoperand1=0x0A;//00001010
constunsignedcharoperand2=0x0C;//00001100
constunsignedcharexpectedAnd=0x08;//00001000
constunsignedcharexpectedOr=0x0E;//00001110
constunsignedcharexpectedXor=0x06;//00000110
constunsignedcharoperand3=0x01;//00000001
constunsignedcharexpectedNot=0xFE;//11111110
testOperator("BitwiseAND",operand1&operand2,expectedAnd);
testOperator("BitwiseOR",operand1|operand2,expectedOr);
testOperator("BitwiseXOR",operand1^operand2,expectedXor);
testOperator("BitwiseNOT",~operand3,expectedNot);
printf("\n");
//--Logicaloperators--//
constunsignedcharF=0x00;//Zero
constunsignedcharT=0x01;//Anynonzerovalue
//Truthtablespackedinarrays
constunsignedcharoperandArray1[4]={T,F,T,F};
constunsignedcharoperandArray2[4]={T,T,F,F};
constunsignedcharexpectedArrayAnd[4]={T,F,F,F};
constunsignedcharexpectedArrayOr[4]={T,T,T,F};
constunsignedcharexpectedArrayXor[4]={F,T,T,F};
constunsignedcharoperandArray3[2]={F,T};
constunsignedcharexpectedArrayNot[2]={T,F};
inti;
for(i=0;i<4;i++)
{
testOperator("LogicalAND",operandArray1[i]&&operandArray2[i],expectedArrayAnd[i]);
}
printf("\n");
for(i=0;i<4;i++)
{
testOperator("LogicalOR",operandArray1[i]||operandArray2[i],expectedArrayOr[i]);
}
printf("\n");
for(i=0;i<4;i++)
{
//Needs !onoperand'sincasenonzerovaluesaredifferent
testOperator("LogicalXOR",!operandArray1[i]!=!operandArray2[i],expectedArrayXor[i]);
}
printf("\n");
for(i=0;i<2;i++)
{
testOperator("LogicalNOT",!operandArray3[i],expectedArrayNot[i]);
}
printf("\n");
return0;
}
voidtestOperator(char*name,unsignedcharwas,unsignedcharexpected)
{
char*result=(was==expected)?"passed":"failed";
printf("%s%s,was:%Xexpected:%X\n",name,result,was,expected);
}
Theoutputoftheaboveprogramwillbe
BitwiseANDpassed,was:8expected:8
BitwiseORpassed,was:Eexpected:E
BitwiseXORpassed,was:6expected:6
BitwiseNOTpassed,was:FEexpected:FE
LogicalANDpassed,was:1expected:1
LogicalANDpassed,was:0expected:0
LogicalANDpassed,was:0expected:0
LogicalANDpassed,was:0expected:0
LogicalORpassed,was:1expected:1
LogicalORpassed,was:1expected:1
LogicalORpassed,was:1expected:1
LogicalORpassed,was:0expected:0
LogicalXORpassed,was:0expected:0
LogicalXORpassed,was:1expected:1
LogicalXORpassed,was:1expected:1
LogicalXORpassed,was:0expected:0
LogicalNOTpassed,was:1expected:1
LogicalNOTpassed,was:0expected:0
Seealso[edit]
Bitmanipulation
Bitwiseoperation
Findfirstset
OperatorsinCandC++
Bitboard
Booleanalgebra(logic)
XORswapalgorithm
XORlinkedlist
References[edit]
^Kernighan;DennisM.Ritchie(March1988).TheCProgrammingLanguage(2nd ed.).EnglewoodCliffs,NJ:PrenticeHall.ISBN 0-13-110362-8.Archivedfromtheoriginalon2019-07-06.Retrieved2019-09-07.RegardedbymanytobetheauthoritativereferenceonC.
^ab"Tutorials-BitwiseOperatorsandBitManipulationsinCandC++".cprogramming.com.
^"Exclusive-ORGateTutorial".BasicElectronicsTutorials.
^"C++Notes:BitwiseOperators".fredosaurus.com.
^"ISO/IEC9899:2011-Informationtechnology--Programminglanguages--C".www.iso.org.
^"Compoundassignmentoperators".IBM.InternationalBusinessMachines.Retrieved29January2022.
Externallinks[edit]
BitwiseOperators
Retrievedfrom"https://en.wikipedia.org/w/index.php?title=Bitwise_operations_in_C&oldid=1094113375"
Categories:BinaryarithmeticC(programminglanguage)Hiddencategories:ArticleswithshortdescriptionShortdescriptionisdifferentfromWikidataUseAmericanEnglishfromMarch2019AllWikipediaarticleswritteninAmericanEnglishArticleswithexampleCcode
Navigationmenu
Personaltools
NotloggedinTalkContributionsCreateaccountLogin
Namespaces
ArticleTalk
English
Views
ReadEditViewhistory
More
Search
Navigation
MainpageContentsCurrenteventsRandomarticleAboutWikipediaContactusDonate
Contribute
HelpLearntoeditCommunityportalRecentchangesUploadfile
Tools
WhatlinkshereRelatedchangesUploadfileSpecialpagesPermanentlinkPageinformationCitethispageWikidataitem
Print/export
DownloadasPDFPrintableversion
Languages
БългарскиСрпски/srpski
Editlinks