Bit Twiddling Hacks.docx

上传人:b****1 文档编号:2125591 上传时间:2023-05-02 格式:DOCX 页数:60 大小:46.57KB
下载 相关 举报
Bit Twiddling Hacks.docx_第1页
第1页 / 共60页
Bit Twiddling Hacks.docx_第2页
第2页 / 共60页
Bit Twiddling Hacks.docx_第3页
第3页 / 共60页
Bit Twiddling Hacks.docx_第4页
第4页 / 共60页
Bit Twiddling Hacks.docx_第5页
第5页 / 共60页
Bit Twiddling Hacks.docx_第6页
第6页 / 共60页
Bit Twiddling Hacks.docx_第7页
第7页 / 共60页
Bit Twiddling Hacks.docx_第8页
第8页 / 共60页
Bit Twiddling Hacks.docx_第9页
第9页 / 共60页
Bit Twiddling Hacks.docx_第10页
第10页 / 共60页
Bit Twiddling Hacks.docx_第11页
第11页 / 共60页
Bit Twiddling Hacks.docx_第12页
第12页 / 共60页
Bit Twiddling Hacks.docx_第13页
第13页 / 共60页
Bit Twiddling Hacks.docx_第14页
第14页 / 共60页
Bit Twiddling Hacks.docx_第15页
第15页 / 共60页
Bit Twiddling Hacks.docx_第16页
第16页 / 共60页
Bit Twiddling Hacks.docx_第17页
第17页 / 共60页
Bit Twiddling Hacks.docx_第18页
第18页 / 共60页
Bit Twiddling Hacks.docx_第19页
第19页 / 共60页
Bit Twiddling Hacks.docx_第20页
第20页 / 共60页
亲,该文档总共60页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

Bit Twiddling Hacks.docx

《Bit Twiddling Hacks.docx》由会员分享,可在线阅读,更多相关《Bit Twiddling Hacks.docx(60页珍藏版)》请在冰点文库上搜索。

Bit Twiddling Hacks.docx

BitTwiddlingHacks

BitTwiddlingHacks

BySeanEronAnderson

seander@cs.stanford.edu

Individually,thecodesnippetshereareinthepublicdomain(unlessotherwisenoted)—feelfreetousethemhoweveryouplease.Theaggregatecollectionanddescriptionsare©1997-2005SeanEronAnderson.Thecodeanddescriptionsaredistributedinthehopethattheywillbeuseful,butWITHOUTANYWARRANTYandwithouteventheimpliedwarrantyofmerchantabilityorfitnessforaparticularpurpose.AsofMay5,2005,allthecodehasbeentestedthoroughly.Thousandsofpeoplehavereadit.Moreover,ProfessorRandalBryant,theDeanofComputerScienceatCarnegieMellonUniversity,haspersonallytestedalmosteverythingwithhisUclidcodeverificationsystem.Whathehasn'ttested,Ihavecheckedagainstallpossibleinputsona32-bitmachine.Tothefirstpersontoinformmeofalegitimatebuginthecode,I'llpayabountyofUS$10(bycheckorPaypal).Ifdirectedtoacharity,I'llpayUS$20.

Contents

Abouttheoperationcountingmethodology

Computethesignofaninteger

Detectiftwointegershaveoppositesigns

Computetheintegerabsolutevalue(abs)withoutbranching

Computetheminimum(min)ormaximum(max)oftwointegerswithoutbranching

Determiningifanintegerisapowerof2

Signextending

●Signextendingfromaconstantbit-width

●Signextendingfromavariablebit-width

●Signextendingfromavariablebit-widthin3operations

Conditionallysetorclearbitswithoutbranching

Conditionallynegateavaluewithoutbranching

Mergebitsfromtwovaluesaccordingtoamask

Countingbitsset

●Countingbitsset,naiveway

●Countingbitssetbylookuptable

●Countingbitsset,BrianKernighan'sway

●Countingbitssetin12,24,or32-bitwordsusing64-bitinstructions

●Countingbitsset,inparallel

●Countbitsset(rank)fromthemost-significantbituptoagivenposition

●Selectthebitposition(fromthemost-significantbit)withthegivencount(rank)

Computingparity(1ifanoddnumberofbitsset,0otherwise)

●Computeparityofawordthenaiveway

●Computeparitybylookuptable

●Computeparityofabyteusing64-bitmultiplyandmodulusdivision

●Computeparityofwordwithamultiply

●Computeparityinparallel

SwappingValues

●Swappingvalueswithsubtractionandaddition

●SwappingvalueswithXOR

●SwappingindividualbitswithXOR

Reversingbitsequences

●Reversebitstheobviousway

●Reversebitsinwordbylookuptable

●Reversethebitsinabytewith3operations(64-bitmultiplyandmodulusdivision)

●Reversethebitsinabytewith4operations(64-bitmultiply,nodivision)

●Reversethebitsinabytewith7operations(no64-bit,only32)

●ReverseanN-bitquantityinparallelwith5*lg(N)operations

Modulusdivision(akacomputingremainders)

●Computingmodulusdivisionby1<

●Computingmodulusdivisionby(1<

●Computingmodulusdivisionby(1<

Findingintegerlogbase2ofaninteger(akathepositionofthehighestbitset)

●Findthelogbase2ofanintegerwiththeMSBNsetinO(N)operations(theobviousway)

●Findtheintegerlogbase2ofanintegerwithan64-bitIEEEfloat

●Findthelogbase2ofanintegerwithalookuptable

●Findthelogbase2ofanN-bitintegerinO(lg(N))operations

●Findthelogbase2ofanN-bitintegerinO(lg(N))operationswithmultiplyandlookup

Findintegerlogbase10ofaninteger

Findintegerlogbase10ofanintegertheobviousway

Findintegerlogbase2ofa32-bitIEEEfloat

Findintegerlogbase2ofthepow(2,r)-rootofa32-bitIEEEfloat(forunsignedintegerr)

Countingconsecutivetrailingzerobits(orfindingbitindices)

●Counttheconsecutivezerobits(trailing)ontherightlinearly

●Counttheconsecutivezerobits(trailing)ontherightinparallel

●Counttheconsecutivezerobits(trailing)ontherightbybinarysearch

●Counttheconsecutivezerobits(trailing)ontherightbycastingtoafloat

●Counttheconsecutivezerobits(trailing)ontherightwithmodulusdivisionandlookup

●Counttheconsecutivezerobits(trailing)ontherightwithmultiplyandlookup

Rounduptothenexthighestpowerof2byfloatcasting

Rounduptothenexthighestpowerof2

Interleavingbits(akacomputingMortonNumbers)

●Interleavebitstheobviousway

●Interleavebitsbytablelookup

●Interleavebitswith64-bitmultiply

●InterleavebitsbyBinaryMagicNumbers

Testingforrangesofbytesinaword(andcountingoccurancesfound)

●Determineifawordhasazerobyte

●Determineifawordhasabyteequalton

●Determineifawordhasbytelessthann

●Determineifawordhasabytegreaterthann

●Determineifawordhasabytebetweenmandn

Computethelexicographicallynextbitpermutation

--------------------------------------------------------------------------------

Abouttheoperationcountingmethodology

Whentotalingthenumberofoperationsforalgorithmshere,anyCoperatoriscountedasoneoperation.Intermediateassignments,whichneednotbewrittentoRAM,arenotcounted.Ofcourse,thisoperationcountingapproachonlyservesasanapproximationoftheactualnumberofmachineinstructionsandCPUtime.Alloperationsareassumedtotakethesameamountoftime,whichisnottrueinreality,butCPUshavebeenheadingincreasinglyinthisdirectionovertime.Therearemanynuancesthatdeterminehowfastasystemwillrunagivensampleofcode,suchascachesizes,memorybandwidths,instructionsets,etc.Intheend,benchmarkingisthebestwaytodeterminewhetheronemethodisreallyfasterthananother,soconsiderthetechniquesbelowaspossibilitiestotestonyourtargetarchitecture.

--------------------------------------------------------------------------------

Computethesignofaninteger

intv;//wewanttofindthesignofv

intsign;//theresultgoeshere

//CHAR_BITisthenumberofbitsperbyte(normally8).

sign=-(v<0);//ifv<0then-1,else0.

//or,toavoidbranchingonCPUswithflagregisters(IA32):

sign=-(int)((unsignedint)((int)v)>>(sizeof(int)*CHAR_BIT-1));

//or,foronelessinstruction(butnotportable):

sign=v>>(sizeof(int)*CHAR_BIT-1);

Thelastexpressionaboveevaluatestosign=v>>31for32-bitintegers.Thisisoneoperationfasterthantheobviousway,sign=-(v<0).Thistrickworksbecausewhensignedintegersareshiftedright,thevalueofthefarleftbitiscopiedtotheotherbits.Thefarleftbitis1whenthevalueisnegativeand0otherwise;all1bitsgives-1.Unfortunately,thisbehaviorisarchitecture-specific.

Alternatively,ifyouprefertheresultbeeither-1or+1,thenuse:

sign=+1|(v>>(sizeof(int)*CHAR_BIT-1));//ifv<0then-1,else+1

Ontheotherhand,ifyouprefertheresultbeeither-1,0,or+1,thenuse:

sign=(v!

=0)|-(int)((unsignedint)((int)v)>>(sizeof(int)*CHAR_BIT-1));

//Or,formorespeedbutlessportability:

sign=(v!

=0)|(v>>(sizeof(int)*CHAR_BIT-1));//-1,0,or+1

//Or,forportability,brevity,and(perhaps)speed:

sign=(v>0)-(v<0);//-1,0,or+1

Ifinsteadyouwanttoknowifsomethingisnon-negative,resultingin+1orelse0,thenuse:

sign=1^((unsignedint)v>>(sizeof(int)*CHAR_BIT-1));//ifv<0then0,else1

Caveat:

OnMarch7,2003,AngusDugganpointedoutthatthe1989ANSICspecificationleavestheresultofsignedright-shiftimplementation-defined,soonsomesystemsthishackmightnotwork.Forgreaterportability,TobySpeightsuggestedonSeptember28,2005thatCHAR_BITbeusedhereandthroughoutratherthanassumingbyteswere8bitslong.Angusrecommendedthemoreportableversionsabove,involvingcastingonMarch4,2006.RohitGargsuggestedtheversionfornon-negativeintegersonSeptember12,2009.

--------------------------------------------------------------------------------

Detectiftwointegershaveoppositesigns

intx,y;//inputvaluestocomparesigns

boolf=((x^y)<0);//trueifxandyhaveoppositesigns

ManfredWeissuggestedIaddthisentryonNovember26,2009.

--------------------------------------------------------------------------------

Computetheintegerabsolutevalue(abs)withoutbranching

intv;//wewanttofindtheabsolutevalueofv

unsignedintr;//theresultgoeshere

intconstmask=v>>sizeof(int)*CHAR_BIT-1;

r=(v+mask)^mask;

Patentedvariation:

r=(v^mask)-mask;

SomeCPUsdon'thaveanintegerabsolutevalueinstruction(orthecompilerfailstousethem).Onmachineswherebranchingisexpensive,theaboveexpressioncanbefasterthantheobviousapproach,r=(v<0)?

-(unsigned)v:

v,eventhoughthenumberofoperationsisthesame.

OnMarch7,2003,AngusDugganpointedoutthatthe1989ANSICspecificationleavestheresultofsignedright-shiftimplementation-defined,soonsomesystemsthishackmightnotwork.I'vereadthatANSICdoesnotrequirevaluestoberepresentedastwo'scomplement,soitmaynotworkforthatreasonaswell(onadiminishinglysmallnumberofoldmachinesthatstilluseone'scomplement).OnMarch14,2004,KeithH.Duggarsentmethepatentedvariationabove;itissuperiortotheoneIinitiallycameupwith,r=(+1|(v>>(sizeof(int)*CHAR_BIT-1)))*v,becauseamultiplyisnotused.Unfortunately,thismethodhasbeenpatentedintheUSAonJune6,2000byVladimirYuVolkonskyandassignedtoSunMicrosystems.OnAugust13,2006,YuriyKaminskiytoldmethatthepatentislikelyinvalidbecausethemethodwaspub

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 人文社科 > 法律资料

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2