Tải bản đầy đủ - 0 (trang)
10 Sign Extension, Zero Extension, Contraction, and Saturation

10 Sign Extension, Zero Extension, Contraction, and Saturation

Tải bản đầy đủ - 0trang

Toextendanunsignedvaluetoalargeroneyoumustzeroextendthe

value.Zeroextensionisveryeasy:JuststoreazerointotheH.O.byte(s)

ofthelargeroperand.Forexample,tozeroextendthe8-bitvalue$82to

16bitsyousimplyaddazerototheH.O.byteyielding$0082.

ZeroExtension:

8bits16Bits32Bits

$80$0080$0000_0080

$28$0028$0000_0028

$9A$009A$0000_009A

$7F$007F$0000_007F

---$1020$0000_1020

---$8086$0000_8086

The80x86providesseveralinstructionsthatwillletyousignorzero

extendasmallernumbertoalargernumber.Table2-6listsagroupof

instructionsthatwillsignextendtheAL,AX,orEAXregister.

Table2-6:InstructionsforExtendingAL,AX,andEAX

Instruction Explanation



cbw();



//ConvertsthebyteinALtoawordinAXviasign

extension.



cwd();



//ConvertsthewordinAXtoadoublewordinDX:AX.



cdq();



//ConvertsthedoublewordinEAXtothequadwordin

EDX:EAX.



cwde();



//ConvertsthewordinAXtoadoublewordinEAX.



Notethatthecwd(convertwordtodoubleword)instructiondoesnotsign

extendthewordinAXtothedoublewordinEAX.Instead,itstoresthe

H.O.wordofthesignextensionintotheDXregister(thenotation

"DX:AX"tellsyouthatyouhaveadoublewordvaluewithDXcontaining

theupper16bitsandAXcontainingthelower16bitsofthevalue).Ifyou



wantthesignextensionofAXtogointoEAX,youshouldusethecwde

(convertwordtodoubleword,extended)instruction.

Thefourinstructionsaboveareunusualinthesensethatthesearethe

firstinstructionsyou'veseenthatdonothaveanyoperands.These

instructions'operandsareimpliedbytheinstructionsthemselves.

Withinafewchaptersyouwilldiscoverjusthowimportantthese

instructionsare,andwhythecwdandcdqinstructionsinvolvetheDX

andEDXregisters.However,forsimplesignextensionoperations,these

instructionshaveafewmajordrawbacks:Youdonotgettospecifythe

sourceanddestinationoperandsandtheoperandsmustberegisters.

Forgeneralsignextensionoperations,the80x86providesanextension

ofthemovinstruction,movsx(movewithsignextension),thatcopies

dataandsignextendsthedatawhilecopyingit.Themovsxinstruction's

syntaxisverysimilartothemovinstruction:

movsx(source,dest);

Thebigdifferenceinsyntaxbetweenthisinstructionandthemov

instructionisthefactthatthedestinationoperandmustbelargerthanthe

sourceoperand.Thatis,ifthesourceoperandisabyte,thedestination

operandmustbeawordoradoubleword.Likewise,ifthesource

operandisaword,thedestinationoperandmustbeadoubleword.

Anotherdifferenceisthatthedestinationoperandhastobearegister;

thesourceoperand,however,canbeamemorylocation.[4]

Tozeroextendavalue,youcanusethemovzxinstruction.Ithasthe

samesyntaxandrestrictionsasthemovsxinstruction.Zeroextending

certain8-bitregisters(AL,BL,CL,andDL)intotheircorresponding16-bit

registersiseasilyaccomplishedwithoutusingmovzxbyloadingthe

complementaryH.O.register(AH,BH,CH,orDH)withzero.Obviously,

tozeroextendAXintoDX:AXorEAXintoEDX:EAX,allyouneedtodois

loadDXorEDXwithzero.[5]

ThesampleprograminListing2-8demonstratestheuseofthesign

extensioninstructions.



Listing2-8:SignExtensionInstructions.

programsignExtension;

#include("stdlib.hhf")

static

i8:int8;

i16:int16;

i32:int32;

beginsignExtension;

stdout.put("Enterasmallnegativenumber:");

stdin.get(i8);



stdout.put(nl,"SignextensionusingCBWandCWDE:",nl,n

mov(i8,al);

stdout.put("Youentered",i8,"($",al,")",nl);



cbw();

mov(ax,i16);

stdout.put("16-bitsignextension:",i16,"($",ax,")",



cwde();

mov(eax,i32);

stdout.put("32-bitsignextension:",i32,"($",eax,")"

stdout.put(nl,"SignextensionusingMOVSX:",nl,nl);

movsx(i8,ax);

mov(ax,i16);



stdout.put("16-bitsignextension:",i16,"($",ax,")",

movsx(i8,eax);

mov(eax,i32);



stdout.put("32-bitsignextension:",i32,"($",eax,")"

endsignExtension;



Signcontraction,convertingavaluewithsomenumberofbitstothe

identicalvaluewithafewernumberofbits,isalittlemoretroublesome.

Signextensionneverfails.Givenanm-bitsignedvalueyoucanalways

convertittoann-bitnumber(wheren>m)usingsignextension.

Unfortunately,givenann-bitnumber,youcannotalwaysconvertittoan

m-bitnumberifm
signednumber,itshexadecimalrepresentationis$FE40.Unfortunately,

themagnitudeofthisnumberistoolargeforan8-bitvalue,soyou

cannotsigncontractitto8bits.Thisisanexampleofanoverflow

conditionthatoccursuponconversion.

Toproperlysigncontractonevaluetoanother,youmustlookattheH.O.

byte(s)thatyouwanttodiscard.TheH.O.bytesyouwishtoremovemust

allcontaineitherzeroor$FF.Ifyouencounteranyothervalues,you

cannotcontractitwithoutoverflow.Finally,theH.O.bitofyourresulting

valuemustmatcheverybityou'veremovedfromthenumber.Examples

(16bitsto8bits):

$FF80canbesigncontractedto$80.

$0040canbesigncontractedto$40.

$FE40cannotbesigncontractedto8bits.

$0100cannotbesigncontractedto8bits.

Anotherwaytoreducethesizeofanintegerisbysaturation.Saturation

isusefulinsituationswhereyoumustconvertalargerobjecttoasmaller

object,andyou'rewillingtolivewithpossiblelossofprecision.Toconvert

avalueviasaturationyousimplycopythelargervaluetothesmaller

valueifitisnotoutsidetherangeofthesmallerobject.Ifthelargervalue

isoutsidetherangeofthesmallervalue,thenyouclipthevalueby

settingittothelargest(orsmallest)valuewithintherangeofthesmaller

object.

Forexample,whenconvertinga16-bitsignedintegertoan8-bitsigned



integer,ifthe16-bitvalueisintherange−128..+127yousimplycopythe

L.O.byteofthe16-bitobjecttothe8-bitobject.Ifthe16-bitsignedvalue

isgreaterthan+127,thenyouclipthevalueto+127andstore+127into

the8-bitobject.Likewise,ifthevalueislessthan−128,youclipthefinal

8-bitobjectto−128.Saturationworksthesamewaywhenclipping32-bit

valuestosmallervalues.Ifthelargervalueisoutsidetherangeofthe

smallervalue,thenyousimplysetthesmallervaluetothevalueclosest

totheout-of-rangevaluethatyoucanrepresentwiththesmallervalue.

Obviously,ifthelargervalueisoutsidetherangeofthesmallervalue,

thentherewillbealossofprecisionduringtheconversion.Whileclipping

thevaluetothelimitsthesmallerobjectimposesisneverdesirable,

sometimesthisisacceptableasthealternativeistoraiseanexceptionor

otherwiserejectthecalculation.Formanyapplications,suchasaudioor

videoprocessing,theclippedresultisstillrecognizable,sothisisa

reasonableconversiontouse.

[4]Thisdoesn'tturnouttobemuchofalimitationbecausesignextension

almostalwaysprecedesanarithmeticoperationthatmusttakeplaceina

register.

[5]ZeroextendingintoDX:AXorEDX:EAXisjustasnecessaryasthe

CWDandCDQinstructions,asyouwilleventuallysee.



2.11ShiftsandRotates

Anothersetoflogicaloperationsthatapplytobitstringsaretheshiftand

rotateoperations.Thesetwocategoriescanbefurtherbrokendowninto

leftshifts,leftrotates,rightshifts,andrightrotates.Theseoperationsturn

outtobeextremelyusefultoassemblylanguageprogrammers.

Theleftshiftoperationmoveseachbitinabitstringonepositiontothe

left(Figure2-8providesanexampleofan8-bitshift).





Figure2-8:ShiftLeftOperation.

Bitzeromovesintobitpositionone,thepreviousvalueinbitpositionone

movesintobitpositiontwo,andsoon.Thereare,ofcourse,two

questionsthatnaturallyarise:"Whatgoesintobitzero?"and"Where

doesthehighorderbitwindup?"We'llshiftazerointobitzeroandthe

previousvalueofthehighorderbitwillbecomethecarryoutofthis

operation.

The80x86providesashiftleftinstruction,shl,thatperformsthisuseful

operation.Thesyntaxfortheshlinstructionis

shl(count,dest);

ThecountoperandiseitherCLoraconstantintherange0..n,wherenis

onelessthanthenumberofbitsinthedestinationoperand(i.e.,n=7for

8-bitoperands,n=15for16-bitoperands,andn=31for32-bitoperands).

Thedestoperandisatypicaldestinationoperand;itcanbeeithera

memorylocationoraregister.

Whenthecountoperandistheconstantone,theshlinstructiondoesthe

operationshowninFigure2-9.





Figure2-9:ShiftLeftOperation.

InFigure2-9,the"C"representsthecarryflag.Thatis,theH.O.bit

shiftedoutoftheoperandmovesintothecarryflag.Therefore,youcan

testforoverflowaftera"shl(1,dest);"instructionbytestingthecarryflag

immediatelyafterexecutingtheinstruction(e.g.,byusing"if(@c)then

…"or"if(@nc)then…").

Intel'sliteraturesuggeststhatthestateofthecarryflagisundefinedifthe

shiftcountisavalueotherthanone.Usually,thecarryflagcontainsthe

lastbitshiftedoutofthedestinationoperand,butInteldoesn'tseemto

guaranteethis.



Notethatshiftingavaluetotheleftisthesamethingasmultiplyingitby

itsradix.Forexample,shiftingadecimalnumberonepositiontotheleft

(addingazerototherightofthenumber)effectivelymultipliesitbyten

(theradix):

1234shl1=12340(shl1meansshiftonedigitpositio

Becausetheradixofabinarynumberistwo,shiftingitleftmultipliesitby

two.Ifyoushiftabinaryvaluetothelefttwice,youmultiplyitbytwotwice

(i.e.,youmultiplyitbyfour).Ifyoushiftabinaryvaluetotheleftthree

times,youmultiplyitbyeight(2*2*2).Ingeneral,ifyoushiftavaluetothe

leftntimes,youmultiplythatvalueby2n.

Arightshiftoperationworksthesameway,exceptwe'removingthedata

intheoppositedirection.Forabytevalue,bitsevenmovesintobit6,bit

6movesintobit5,bit5movesintobit4,andsoon.Duringarightshift,

we'llmoveazerointobit7,andbit0willbethecarry-outoftheoperation

(seeFigure2-10).





Figure2-10:ShiftRightOperation.



Asyouwouldprobablyexpect,the80x86providesashrinstructionthat

willshiftthebitstotherightinadestinationoperand.Thesyntaxisthe

sameastheshlinstructionexcept,ofcourse,youspecifyshrrather

thanshl:

shr(count,dest);

ThisinstructionshiftsazerointotheH.O.bitofthedestinationoperand;it

shiftsalltheotherbitsoneplacetotheright(thatis,fromahigherbit

numbertoalowerbitnumber).Finally,bit0isshiftedintothecarryflag.If

youspecifyacountofone,theshrinstructiondoestheoperationshown

inFigure2-11.





Figure2-11:ShiftRightOperation.

Onceagain,Intel'sdocumentssuggestthatshiftsofmorethanonebit

leavethecarryinanundefinedstate.

Becausealeftshiftisequivalenttoamultiplicationbytwo,itshouldcome

asnosurprisethatarightshiftisroughlycomparabletoadivisionbytwo

(or,ingeneral,adivisionbytheradixofthenumber).Ifyouperformn

rightshifts,youwilldividethatnumberby2n.

Thereisoneproblemwithshiftrightswithrespecttodivision:Ashiftright

isonlyequivalenttoanunsigneddivisionbytwo.Forexample,ifyoushift

theunsignedrepresentationof254($FE)oneplacetotheright,youget

127($7F),exactlywhatyouwouldexpect.However,ifyoushiftthe

binaryrepresentationof−2($FE)totherightoneposition,youget127

($7F),whichisnotcorrect.Thisproblemoccursbecausewe'reshiftinga

zerointobit7.Ifbit7previouslycontainedaone,we'rechangingitfrom

anegativetoapositivenumber.Notagoodthingwhendividingbytwo.

Tousetheshiftrightasadivisionoperator,wemustdefineathirdshift

operation:arithmeticshiftright.[6]Anarithmeticshiftrightworksjustlike

thenormalshiftrightoperation(alogicalshiftright)withoneexception:



insteadofshiftingazerointothehighorderbit,anarithmeticshiftright

operationcopiesthehighorderbitbackintoitself,thatis,duringtheshift

operationitdoesnotmodifythehighorderbit,asFigure2-12shows.





Figure2-12:ArithmeticShiftRightOperation.

Anarithmeticshiftrightgenerallyproducestheresultyouexpect.For

example,ifyouperformthearithmeticshiftrightoperationon−2($FE)

youget−1($FF).Keeponethinginmindaboutarithmeticshiftright,

however.Thisoperationalwaysroundsthenumberstotheclosest

integerthatislessthanorequaltotheactualresult.Basedon

experienceswithhighlevelprogramminglanguagesandthestandard

rulesofintegertruncation,mostpeopleassumethismeansthata

divisionalwaystruncatestowardzero.Butthissimplyisn'tthecase.For

example,ifyouapplythearithmeticshiftrightoperationon−1($FF),the

resultis−1,notzero.Minusoneislessthanzero,sothearithmeticshift

rightoperationroundstoward−1.Thisisnota"bug"inthearithmeticshift

rightoperation;itjustusesadifferent(thoughvalid)definitionofinteger

division.

The80x86providesanarithmeticshiftrightinstruction,sar(shift

arithmeticright).Thisinstruction'ssyntaxisnearlyidenticaltoshland

shr.Thesyntaxis

sar(count,dest);

Theusuallimitationsonthecountanddestinationoperandsapply.This

instructionoperatesasshowninFigure2-13ifthecountisone.





Figure2-13:SAR(1,dest)Operation.



Onceagain,Intel'sdocumentssuggestthatshiftsofmorethanonebit

leavethecarryinanundefinedstate.

Anotherpairofusefuloperationsarerotateleftandrotateright.These

operationsbehaveliketheshiftleftandshiftrightoperationswithone

majordifference:Thebitshiftedoutfromoneendisshiftedbackinatthe

otherend.Figures2-14and2-15diagramtheseoperations.





Figure2-14:RotateLeftOperation.





Figure2-15:RotateRightOperation.

The80x86providesrol(rotateleft)andror(rotateright)instructionsthat

dothesebasicoperationsontheiroperands.Thesyntaxforthesetwo

instructionsissimilartotheshiftinstructions:

rol(count,dest);

ror(count,dest);

Onceagain,theseinstructionsprovideaspecialbehavioriftheshift

countisone.Underthisconditionthesetwoinstructionsalsocopythebit

shiftedoutofthedestinationoperandintothecarryflag,asFigures2-16

and2-17show.







Figure2-16:ROL(1,Dest)Operation.





Figure2-17:ROR(1,Dest)Operation.

Notethat,Intel'sdocumentssuggestthatrotatesofmorethanonebit

leavethecarryinanundefinedstate.

Itwillturnoutthatitisoftenmoreconvenientfortherotateoperationto

shifttheoutputbitthroughthecarryandshiftthepreviouscarryvalue

backintotheinputbitoftheshiftoperation.The80x86rcl(rotate

through,carryleft)andrcr(rotatethrough,carryright)instructions

achievethisforyou.Theseinstructionsusethefollowingsyntax:

rcl(count,dest);

rcr(count,dest);

Asistruefortheothershiftandrotateinstructions,thecountoperandis

eitheraconstantortheCLregisterandthedestinationoperandisa

memorylocationorregister.Thecountoperandmustbeavaluethatis

lessthanthenumberofbitsinthedestinationoperand.Foracountvalue

ofone,thesetwoinstructionsdotherotationshowninFigures2-18and

2-19.





Figure2-18:RCL(1,Dest)Operation.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

10 Sign Extension, Zero Extension, Contraction, and Saturation

Tải bản đầy đủ ngay(0 tr)

×