but how do it know? - the basic principles of computers for everyone
TRANSCRIPT
BUTHOWDOITKNOW?
TheBasicPrinciplesofComputersForEveryone
By
J.ClarkScott
Copyright©2009byJohnClarkScott
ComputerdesignincorporatedhereinCopyright©2009byJohnClarkScott
AllRightsReserved
PublishedbyJohnC.Scott,Oldsmar,FL34677
ISBN978-0-615-30376-5
buthowdoitknow.com
Coverart,photographyanddesignbyAlexanderC.ScottIIIartbyalexscott.com
PrintedintheUnitedStatesofAmerica
FirstEdition:July2009
10987654321
Introduction
Thetitleofthisbookisthepunchlineofanoldjokethatgoeslikethis:
Joeisaverynicefellow,buthasalwaysbeenalittleslow.Hegoesintoastorewhereasalesmanisstandingonasoapboxinfrontofagroupofpeople.Thesalesmanispitchingthemiraclenewinvention,theThermosbottle.Heissaying,"Itkeepshotfoodhot,andcoldfoodcold...."Joethinksaboutthisaminute,amazedbythisnewinventionthatisabletomakeadecisionaboutwhichoftwodifferentthingsitissupposedtododependingonwhatkindoffoodyouputinit.Hecan'tcontainhiscuriosity,heisjumpingupanddown,wavinghisarmintheair,saying"but,but,but,but..."Finallyheblurtsouthisburningquestion"Buthowdoitknow?"
Youmayormaynothavelaughedatthejoke,butthepointisthatJoelookedatwhatthisThermosbottlecoulddo,anddecidedthatitmustbecapableofsensingsomethingaboutitscontents,andthenperformingaheatingorcoolingoperationaccordingly.Hethoughtitmustcontainaheaterandarefrigerator.Hehadnoideaofthemuchsimplerprincipleonwhichitactuallyoperates,whichisthatheatalwaysattemptstomovefromahotterareatoacoolerarea,andalltheThermosdoesistoslowdownthismovement.Withcoldcontents,theoutsideheatisslowedonitswayin,andwithhotcontents,theheatisslowedonitswayout.Thebottledoesn'thaveto"know"inordertofulfillitsmission,anddoesn'theatorcoolanything.Andeventually,thecontents,hotorcold,doendupatroomtemperature.ButJoe'sconceptofhowthebottleworkedwasfarmorecomplicatedthanthetruth.
Sothereasonforthebooktitle,isthatwhenitcomestocomputers,peoplelookatthem,seewhattheycando,andimagineallsortsofthingsthatmustbeinthesemachines.Ortheyimagineallsortsofprinciplesthattheymustbebasedon,andthereforewhattheymaybecapableof.Peoplemayassignhumanqualitiestothemachine.Andmorethanafewfindthemselvesinsituationswheretheyfeelthattheyareembarrassingthemselves,likeourfriendinthejoke,Joe.
Butcomputersareactuallyquiteeasytounderstand.OfcoursecomputershaveagreaternumberofpartsthanaThermosbottle,buteachpartisextremelysimple,andtheyalloperateonaverysimple,veryeasytounderstandprinciple.
WiththeThermos,theprincipleisthatofthemotionofheat.Thisissomething
wecanobserveinlife.Weseeicecubesmeltingwhentheyareremovedfromthefreezer,andweseethehotmealcoolingoffonthetablewhenthefamilyislatefordinner.
Inthecomputer,theprincipleonwhichitoperateshastodowithelectricity,butthatdoesn'tmeanthatitishardtounderstand.Ifyouhaveobservedthefactthatwhenyouturnonalightswitch,alightbulblightsup,andwhenyouturntheswitchoff,thelightgoesdark,thenyouhaveobservedtheprincipleonwhichcomputersoperate.Thatisaboutallyouneedtoknowaboutelectricitytounderstandcomputers.
JUSTTHEFACTSMA'AM
Thisbookisnotprimarilyintendedtobeatextbook.Therearenoproblemstodoattheendofeachchapter.Itsintentionissimplytodemystifythesubjectofcomputersforanyonewhohaseverwonderedwhat'sgoingoninsideofthatbox.Ofcourse,italsomakesaperfectintroductiontocomputersforayoungpersonwhowillultimatelygoontogetaPhDinComputerScience.Butitshouldbeeasilyunderstandablebyhousewives,seniorcitizensandchildrenwhocanreadwell.Itshouldbeunderstandabletoplumbersandstreetsweepers.Itrequiresnoprevioustechnicaleducation.Itonlyrequiresthatyoucanreadthelanguage,youcanturnalightbulbonandoff,andyoucandoverysimpleadditionontheorderof8+5=13.
Thisbookpresentsthecompleteessentialsthatmakeupacomputer.Itpresentseverypieceandpart,intheproperordersothateachonewillmakesense,andcanbeunderstood.Everypartisexplainedfully,andeverynewwordisdefinedthoroughlywhenitisfirstused.Anyattempttosimplifythesubjectfurtherwouldleavegapsinthebigpicturewheresomeonewouldstillhavetoguesshowthepartsworktogether,andyoujustwouldn'teverhavethat"Aha,Igetit!"momentthatIthinkyou'llsoonhave.
Thisbookisnota'dumbed-down'versionofsomecollegetextbook.Itisacompleteexplanationofthebasicprinciplesofcomputers.Itisatechnicalbook,butsoisacookbookandsoisadriver'seducationhandbook.Thisbookjuststartsatthebeginninganddefineseveryitemneededtounderstandthemachine.Nomatterwhatsomeonealreadyknowsaboutcomputers,thiswillfillinanymissingpiecesandputthemalltogetherintosomethingthatmakessense.
Evenourfriend,Joe,couldunderstandthisbookwithdiligentstudy.Therearethousandsofwordsandideasassociatedwiththefieldofcomputersthatmakethewholesubjectseemlikeamess.Butthebasicconceptsunderlyingthemaresimple.
Inthisbook,therewillnotbevolumesoftriviaabouttheconstructionorhistoryofcomputers,justtheessentials,nomoreandnoless.Eachpartofthecomputerhasasimplefunction,andwhentheyareconnectedtogether,youendupwithausefulmachinecalledacomputer.
Thereisnothingtomemorizeinthisbook.Eachchapterisdesignedtogiveyouanewideathatyoudidn'thavebefore,orifitissomethingthatyouhadheardaboutpreviously,italwaysseemedconfusing.Eachideaisverysimple,andone
thingleadstothenext.Eachchapterpresentsanidea.Eachideaissimpleandeasytounderstand.Laterchapterspresentideasthatbuildontheideasfrompreviouschapters.
Ifsomeoneweretowriteabookabouthowtobuildahouse,therecouldbevariouslevelsofdetail.Thesimplestbookwouldsay,"layafoundation,putupthewalls,coverwitharoof,putinplumbingandelectrical,andyou'redone."Thatwouldnotbeenoughdetailforsomeonewhodidn'talreadyhavesomeexperienceusingahammerandsawandinstallingafaucetandwiringalightswitch.
Attheotherendofthespectrumwouldbeabookthathadseparatechaptersforeverypossibletypeoffoundation,thedifferentkindsofdirtyoumighthavetodigin,formulasforadozendifferentkindsconcrete,chartsofweatherconditionsthatareoptimumforlayingfoundations,etc.Thatwouldbefartoomuchinformation.Therewouldbesomanydetails,thatwhatwasreallyimportantwouldgetlost.
Thisbookattemptstogivejustenoughdetailtoseewhateverycomputerhasincommonandhowtheywork,nothowtobuildthebiggestorbestcomputerevermade.Itisnotaboutanyspecificbrandofcomputer.Itisnotabouthowtouseacomputer.Ifitwereabookaboutbuildingahouse,itwouldprobablydescribeasimpleplanforasturdygardenshedwithasinkandonebarelightbulb,showingthesizeandshapeofeverypieceofwood,wheretoputallthenails,howtohangthedoorandhowtoputthewaterpipestogethersotheywouldn'tleak.Itwouldnotshowhowtobuildanythingascomplicatedasafancycurvedoakstaircase.
Wearegoingtoshowtheonesimplepartthatcomputersaremadeof,andthenconnectabunchofthemtogetheruntilwehavebuiltacompletecomputer.Itisgoingtobealotsimplerthanyoueverimagined.
SPEED
Computersseemmysteriousandmagical.Howcantheydowhattheydo?Theyplaygames,theydrawpictures,they'know'yourcreditrating.Thesemachinesarecapableofdoingallsortsofstrangeandwondrousthings.Yettheyaresimple.Theycandoonlyaveryfew,verysimplethings.And,theycanonlydooneofthesesimplethingsatatime.Theyappeartobedoingcomplexthings,onlybecausetheydoahugenumberofsimplethingsoneafteranotherinasmallamountoftime.Theresult,asinavideogame,isverycomplexinappearance,butinreality,isverysimple,justveryveryfast.
Computersaredesignedtodoasmallnumberofspecificsimplethings,andtodothesethingsquickly,oneaftertheother.Whichsimplethingsaredone,andinwhatorder,determineswhatsortoftaskthecomputeraccomplishesinanygiventime,butanythingthecomputerdoesconsistsofnothingoutsideofitslimitedcapabilities.
Onceyouseewhatacomputerismadeupof,youwillcometorealizehowitisthattheycandowhattheydo,exactlywhatsortsofthingstheyarecapableof,andalso,whattheyarenotcapableof.
Sothesecretofcomputersisnotthattheyarecomplex,ratheritistheirspeed.Let'slookatexactlyhowfasttheirspeedis.
Sincecomputersworkonelectricity,theirspeedisrelatedtothespeedofelectricity.Youmayrememberhearingthatthespeedoflightis186,000milespersecond.That'sprettydarnedfast.Lightcangoaroundtheentireearthseventimesinonesecond,orfromtheEarthtotheMooninaboutasecondandahalf.Perthephysicists,electricityhasmanypropertiesincommonwithlight,anditsspeed,whentravelinginawire,getssloweddowntoabouthalfthespeedoflight.Butstill,goingallthewayaroundtheEarththreeandahalftimesinonesecondisextremelyfast.
Asapointofcomparison,imagineitisahotdayandyouhaveanelectricfansittingonthetableblowingcoolaironyou.Thefanisspinningaroundsofastthatthebladesareablur,butitisonlyspinningaroundabout40timeseachsecond.Apointontheedgeofoneofthosebladeswillonlytravelabout150feetinthatsecond,itwilltake35secondsforthatpointtotraveljustonemile.
Sincethefanbladesarealreadyablur,itmaybehardtoimaginethemgoingjusttentimesfaster.Ifitdid,thatfanwouldbeputtingoutquiteabreeze.Andifyou
couldmakeitgoahundredtimesfaster,itwouldalmostcertainlyself-destruct,withfanbladesbreakingoffandgettingstuckintheceiling.Butelectricitytravelinginthesamecirclewouldgoaroundaboutahundredmilliontimesinonesecond,that'stwoandahalfmilliontimesfasterthanthefanblades.That'sfast.
Amillionisaverylargenumber.Ifyoutookabigsheetofpaperthatwas40inchessquareandtookarulerandplaceditatthetopedge,anddrew25dotsperinchalongthetopedgeofthepaper,youwouldhavetodrawonethousanddotstogetacrossthatsheetofpaper.Ifyouthenmovedtherulerdownthepage1/25 ofaninch,anddrewanotherthousanddots,andkeptdoingthat,youwouldhavetomovetherulerdownthepageonethousandtimes,eachtimedrawingonethousanddots.Ifyoucouldcompletesuchaboringtask,youwouldendupwithapieceofpaperwithamilliondotsonit.That'salotofdotsoralotofanything.Andjusttofinishthethought,ifyoucouldfindathousandpeoplewhowouldeachdrawoneofthesemilliondotsheets,andstackedupthosethousandsheetsinapile,youwouldthenhaveabilliondots.
Nowlet'ssaythattheelectricitymovingaroundinsidethecomputercanaccomplishsomesimpletaskbytravelingonefoot.Thatmeansthatthecomputercoulddo500millionsimplethingsinonesecond.Againforcomparison,thefanonthetablewillspinfor7hourstogoaroundjustonemilliontimesanditwilltakeafullsixmonthsforittospinaround500milliontimes.
Whenyoutalkaboutthespeedthatelectricitycanmovebetweenpartsinsidethecomputer,someofthepartsyoucanseeareafootapart,somearecloser,aninch,atenthofaninch.Andinsidethesepartsareamultitudemorepartsthatareveryclosetoeachother,somejustthousandthsofaninchapart.Andtheshorterthedistancetheelectricityhastotravel,thesooneritgetsthere.
Thereisnopointinsayinghowmanythingstoday'scomputersdoinasinglesecond,becausethatwoulddatethisbook.Computermanufacturerscontinuetoproducenewcomputersthatgotwiceasfastasthefastestcomputersofonlytwoorthreeyearspast.Thereisatheoreticallimittohowfasttheycango,butengineerskeepfindingpracticalwaystogetaroundthetheoriesandmakemachinesthatgofasterandfaster.
Duringallofthistimethatcomputershavebeengettingfaster,smallerandcheaper,thethingsthatcomputersdo,reallyhavenotchangedsincetheywerefirstinventedinthe1940's.Theystilldothesamefewsimplethings,justfaster,
th
cheaper,morereliablyandinasmallerpackage.
Thereareonlyafewsectionstoacomputer,andtheyareallmadeoutofthesamekindsofparts.Eachsectionhasaspecificmission,andthecombinationofthesepartsintoamachinewasatrulymarvelousinvention.Butitisnotdifficulttounderstand.
Language
Inthisbook,wearegoingtoneedtodefinesomewordsthatareusedtodescribethepartsinsideacomputer.
Insomeprofessions,notablytheMedicalandLegal,thereisatendencytomakeupalotofnewwords,andtotakethemfromtheancientGreekandLatinlanguages,andtomakethemlongandhardtopronounce.
Intheworldofcomputers,itseemsthatthepioneerinventorswerealessformalsortofpeople.Mostofthewordstheyusedaresimplewordsfromeverydaylanguage,wordsthatalreadyexisted,butareusedinanewway.
Someofthenewwordsarewordswealreadyknow,usedasadifferentpartofspeech,likeanexistingnounnowusedasaverb.Someofthewordsareacronyms,thefirstlettersfromthewordsofaphrase.
Eachwordwillbedescribedthoroughlywhenitisfirstused.Andalthoughtherearethousandsofwordsandacronymsinuseifyouconsidertheentirecomputerindustry,thereareonlyaboutadozenortwowordsneededtounderstandthecomputeritself.Youhaveprobablyheardsomeofthesewordsbefore,andfiguredoutwhattheymeantfromhowtheywereused,butnowyouwillgettheproperandfulldefinitions.Inmanycasesyoumayfindthattheyaresimplerthanyouthought.
JUSTALITTLEBIT
Whatisinacomputer?Itshowsyoustillpictures,movingpictures,music,yourcheckbook,lettersyouhavewritten,itplaysvideogames,communicatesallaroundtheworld,andmuchmuchmore.Butaretherepicturesinsidethecomputer?Ifyougotoutamicroscopeandknewwheretolook,couldyoufindlittlepicturessomewhereinsidethecomputer?Wouldyousee"A"sand"B"sand"8"sand"12"smovingaroundintheresomewhere?
Theanswerisno,therearenopictures,numbersorlettersinacomputer.Thereisonlyonekindofthinginacomputer.Therearealargenumberofthiskindofthing,butthereisonlyonekindofthinginthere.Itiscalledabit.
Whenyouflipacoinupintheair,andletitfallontheground,itwillenduponthefloorinoneoftwopossiblestates-witheithertheheadshowing,orthetail.
Thelightinyourlivingroom(assumingyouhaveaswitchandnotadimmer)canbeeitheronoroff.
Thelockonyourfrontdoorcanbeeitherlockedorunlocked.
Whatdoallofthesethingshaveincommon?Theyareallplacesthatcontainathingthatcanbeinoneoftwopossiblestates.Thisisthedefinitionofabit.
Abitissomekindofaphysicalobjectthathasasizeandalocationinspace,andithassomequalityaboutitself,thatatanygiventimecanbeinoneoftwopossiblestates,andmaybemadetochangebackandforthbetweenthosetwostates.
Alumpofclayisnotabit.Itcanbemoldedintoaball,acube,apancake,aring,alog,afaceoranythingelseyoucanthinkof.Ithasasizeandalocationinspace,buttherearetoomanystatesthatitcanbeinforittobecalledabit.Ifyoutookthatlumpofclay,flatteneditout,scratched"yes"ononesideofit,and"no"ontheotherside,andthenputitinakilnandfiredituntilitwashard,thenyoumightbeabletocallitabit.Itcouldsitonatablewitheitherthe"yes"or"no"showing.Thenitwouldonlyhavetwostates.
Youhaveprobablyheardofbitsbeforeinrelationtocomputers,andnowyouknowwhattheyare.Inacomputer,thebitsarenotlikethecoinorthelock,theyaremostlikethelight.Thatis,thebitsinacomputerareplacesthateitherhaveelectricityortheydonot.Inacomputer,thebitsarevery,verysmallandthereareaverylargenumberofbits,butthat'sallthatisinthere.
Likethelightinthelivingroom,thebitiseitheronoroff.Inthelivingroom,thereiselectricityinthewallcomingintotheswitch.Whenyouturntheswitchon,theelectricitygoesfromtheswitch,throughthewiresinthewallandceiling,intothelightsocketandthenintothelightbulb.Sothisbitinthelivingroomisseveralfeetlong,itincludestheswitch,thewires,thesocketandthelightbulb.Inacomputer,bitsaremostlytiny,actuallymicroscopic.Also,thecomputerbitdoesn'thaveamechanicalswitchatoneendoralightbulbattheother.Ifyouremovedthelightbulbfromthesocketinthelivingroom,theswitchwouldstillsendelectricitytothesocketwhenitwason,anditwouldstillbeabit-youjustwouldn'tbeabletoseewhetheritwasonoroffbylookingatalightbulb.Yourcomputerhassomethingresemblingswitches,likethekeysonthekeyboard,andsomethingresemblinglightbulbs,likethetinydotsonthescreen,butmostofthebitsareinsideandunseen.
Thisisbasicallyallthereisinacomputer-bits.Therearelotsandlotsofthem,andtheyarearrangedandconnectedupinvariousways,whichwewillexamineindetailasthebookprogresses,butthisiswhatisinsideallcomputers-bits.Abitisalwaysinoneofitstwopossiblestates,eitherofforon,andtheychangebetweenonandoffwhentheyaretoldtodoso.Computerbitsaren'tlikethecointhathastophysicallyflipovertochangefromonestatetotheother.Bitsdon'tchangeshapeorlocation,theydon'tlookanydifferent,theydon'tmoveorrotateorgetbiggerorsmaller.Acomputerbitisjustaplace,ifthereisnoelectricityinthatplace,thenthebitisoff.Whenelectricityispresent,thenthebitison.
Ifyouwanttochangeacoinfromshowingheadstoshowingtails,youhavetophysicallymoveittoflipitover,whichtakessomeamountoftime.Becausetheonlythingthathastomoveinacomputerbitistheelectricity,changingit'sstatefromofftoon,orontooffcanhappenmuchmorequicklythananythingthathastobemovedphysically.
Asanotherexample,rememberthewildAmericanwestfromthemovies?Therewerelittletownsseparatedbyvastdistances.Thebiggertownswouldhaveatelegraphoffice.Inthisofficewasaguywearingafunnyhatwhohadaspring-loadedswitchcalledakey,andhewouldsendmessagesbypressingthiskeyonandoffincertainpatternsthatrepresentedthelettersofthealphabet.Thatkeywasconnectedtoabattery(yestheyhadbatteriesbackthen)andawirethatwasstrungalongpolesuntilitgottoanothertown.Thekeysimplyconnectedthebatterytothewirewhenitwaspressed,anddisconnectedthebatterywhenthekeywasnotpressed.Intheothertowntherewasanothertelegraphoffice,the
wirecameintothatoffice,theendofitwaswrappedaroundanironrod(whichturnsintoamagnetwhenthereiselectricityinthewire,)themagnetizedrodattractedalittlebarofironheldnearbywithaspring,andmadeaclickingsoundeverytimetheelectricitycameon.Theguyintheofficelistenedtothepatternoftheclickingandwrotedownthelettersofthemessage.Theymighthaveusedalightbulbinsteadoftheclicker,exceptthatlightbulbshadnotyetbeeninvented.
Thepointofbringingupthissubject,isthatthiswholetelegraphmachine,fromthekeythatgetspressedinonetown,throughthelongwirethattravelstoanothertownmanymilesaway,totheclicker,thiswholeapparatuscomprisesjustonesinglebit.Itisaplacethatcaneitherhaveornothaveelectricity,andgoesonandoffasitistold.Andthismethodofcommunicationrevolutionizedtheworldinmanyways.Butthisveryimportantinventionofthe1840sconsistedofnothingmorethanonebit.
SoIhopethisbeginstosimplifythesubjectofcomputersforyou.Thereisonlyonethinginsidecomputers,bits.Lotsofthemtobesure,butwhenyouunderstandbits,youunderstandwhat'sinthere.
WHATTHE...?
Imagineitisabrightsunnyday,andyouwalkintoaroomwithlotsofopenwindows.Younoticethattheceilinglightison.Youdecidethatthisisawaste,andyouaregoingtoturnthelightoff.Youlookatthewallnexttothedoorandseeaswitchplatewithtwoswitches.Soyouassumethattheoneclosertothedoorisfortheceilinglight.Butthenyounoticethattheswitchisalreadyoff.Andtheotherswitchisofftoo.Sothenyouthink"well,maybesomeoneinstalledtheswitchupsidedown,"soyoudecidetofliptheswitchanyway.Youflipitonandoffbutnothinghappens,theceilinglightstayslit.Sothenyoudecidethatitmustbetheotherswitch,andyouflipiton,off,on,off.Againnothinghappens,thatceilinglightcontinuestoshineatyou.Youlookaround,thereisnootherdoor,therearenootherswitches,noapparentwaytoturnoffthisdarnedlight.Itjusthastobeoneofthesetwoswitches,whobuiltthiscrazyhouseanyway?Soyougraboneswitchwitheachhandandstartflippingthemwildly.Thensuddenlyyounoticetheceilinglightflickeroffbriefly.Soyouslowdownyourswitchflippingandstopwhentheceilinglightisoff.Bothswitchessay"on",andthelightisnowoff.Youturnoneswitchoff,thenon,andthelightgoeson,thenbackoff.Thisisbackwards.Oneswitchoffequalslighton?Sothenyouturntheotherswitchoff,thenon,thesamething,thelightgoeson,thenbackoff.Whattheheck?Anyway,youfinallyfigureouthowitworks.Ifbothswitchesareon,thelightgoesoff.Ifoneortheotherorbothswitchesareoff,thentheceilinglightison.Kindofgoofy,butyouaccomplishwhatyouintended,youturnbothswitcheson,thelightgoesoff,andyougettheheckoutofthiscrazyroom.
Nowwhatisthepurposeofthislittlestoryabouttheoddlightswitches?Theansweris,thatinthischapterwearegoingtopresentthemostbasicpartthatcomputersaremadeof.Thispartworksexactlylikethelightingsysteminthatstrangeroom.
Thiscomputerpartisasimpledevicethathasthreeconnectionswheretheremayormaynotbesomeelectricity.Twoofthoseconnectionsareplaceswhereelectricitymaybeputintothedevice,andthethirdconnectionisaplacewhereelectricitymaycomeoutofthedevice.
Ofthethreeconnections,twoofthemarecalled"inputs,"becauseelectricitycanbesenttothemfromsomewhereelse.Thethirdconnectioniscalledthe"output"becauseelectricitycancomeoutofitandthenbesentsomewhereelse.
Thiscomputerpartisadevicethatdoessomethingwithbits.Ifyouhavetwobits,andyouconnectthosetwobitstotheinputs,thisdevice"looks"atthosetwobits,and"decides"whethertoturntheoneoutputbitonoroff.
Thewayit"decides"isverysimple,andisalwaysthesame.Ifbothinputsareon,theoutputwillbeoff.Ifoneorbothoftheinputsareoff,thentheoutputwillbeon.That'sjustthewaythattheroomwiththeoddlightswitchesworked.
Rememberthatthereisnothingbutbitsinsidethecomputer.Thissimpledeviceiswherebitscomefromandwheretheygoto.The"decision"thatthisdevicemakesishowbitscometobeturnedonandoffinacomputer.
Twobitsgointothedevice,andonebitcomesout.Twobitscomefromsomewhereelse,areexaminedbythedevice,andanewthirdbitisgeneratedsothatitmaygosomewhereelse.
Ifyouhavebeenextraobservant,youmayhaveaskedyourselfthisquestion:"whenbothinputsareoff,theoutputison,so....howdoyougetelectricityattheoutputifbothinputsareoff?"Well,thatisanexcellentquestion,andtheexcellentansweristhateveryoneofthesedevicesisalsoconnectedtopower.Likeeveryapplianceortablelampinyourhouse,whereeachhasaplugwithtwopins,thisdevicehasapairofwires,oneofwhichisconnectedtoaplacewheretheelectricityisalwayson,andtheotherisconnectedtoaplacewheretheelectricityisalwaysoff.Thisiswheretheelectricityfortheoutputcomesfrom.Whensomeonebuildsacomputer,theyhavetomakeallofthosepowerconnectionstoeachoneofthosepartsinordertohaveitwork,butwhenwearedrawingdiagramsofparts,howtheyareconnected,andwhattheywilldo,wewon'tbotherdrawingthepowerwires-theywouldjustclutterupthedrawing.Itisunderstoodthateachparthasitspowerconnection,andwedon'tworryaboutit.Justunderstandthatitisthere,andwewon'tmentionitanymorefortherestofthebook.Iwouldn'thaveevenmentionedithereexceptthatIfiguredthatyou'dprobablyaskyourselfthatquestionsoonerorlater.
NowIknowIsaidthatyoudon'thavetounderstandmuchaboutelectricitytounderstandcomputers.Hereisascomplicatedasitgets.Thereareactuallyahalfdozenelectronicpartsinsideofthisdevicethatmakeitwork,butwearenotgoingtoexaminethosepartsinthisbook.Someonewhohasanelectronicsbackgroundcouldlookatwhat'sinthere,andinabout30secondswouldsay"Ohyeah,ifbothinputsareon,theoutputwillbeoff,andforanyothercombinationtheoutputwillbeon,justlikethebooksays."Andthenthatpersoncouldgoaheadandreadthisbookwithouteverhavingtothinkaboutwhat'sin
thereagain.Someonewhodoesn'tknowelectronicsmissesoutonthosefewsecondsofunderstanding,butthisbookisthesameforeveryone.
Innormalhousewiring,oneswitchturnsonelightonandoff.Inthecomputer,ittakestwoswitches,andit'ssortofbackwardsinthattheybothhavetobeontoturnthelightoff.Butifyouacceptthefactthatsomethingcouldbemadethatoperatesthisway,youcanthenunderstandhoweverythinginthecomputerworks.
ThistypeofcomputerpartisinfacttheONLYtypeofpartrequiredtobuildacomputer.Ofcourseittakesalotofthemtobuildacompletecomputer,butwithenoughofthem,youcanmakeanytypeofcomputer.Sothereyougoagain,seehowsimpleacomputeris?Itisjustfullofthislittletypeofthing-alotofthemtobesure,butthisisallthereis.
Nowweneedtogivethisdeviceaname,thisthinginsidethecomputerthatbitsaremadeof,itiscalleda"gate."Ican'tfindagoodreasonwhyitiscalledagate,agateinafenceletspeoplethroughwhenitisopen,andstopspeoplewhenitisclosed.Acomputergategeneratesathirdbitfromtwootherbits,itdoesn'topenandcloseorstoporletanythingthrough.Themeaningofthiscomputerterm"gate"doesn'tseemtofitintothecommonmeaningoftheword,butsorry,Ididn'tmakeupthename,that'sjustwhatitiscalled.You'llgetusedtoit.Atleastitisn'tsomelongwordfromtheancientGreek.
Inthenextfewchapters,wearegoingtoshowhowwecandosomethingusefulbyconnectingseveralgatestogether.Wewillusedrawingslikethefollowing.The'D'shapewiththelittlecircleatitstiprepresentsthedevicewehavedescribed,andthelinesrepresentthewiresgoinginandcomingoutofitthatgetattachedtootherpartsofthecomputer.Thepictureontheleftshowsagatecompletewithitspowerwires,butaspromised,wewon'tbeconcernedwiththemfortherestofthisbook.Thedrawingontherightshowseverythingweneed:
Thisisarepresentationofagate.Thetwowiresontheleft(aandb)arethe
inputs,andthewireontheright(c)istheoutput.Allthreewiresarebits,whichmeansthattheyareeitheronoroff.Eachinputbitcomesfromsomewhereelseinthecomputerandiseitheronoroffdependingonwhatishappeningwhereitcamefrom,andthenthisgatesetsitsoutputonoroffdependingonthestatesofitstwoinputs.
Sometimesitisusefultomakealittlechartthatshowshowthevariousinputcombinationscreatetheoutput,likethis:
Eachlineshowsonepossiblecombinationoftheinputs,andwhattheoutputwillbeunderthosecircumstances.
Comparethislittlechartwiththeexperiencewiththeoddroomwiththetwolightswitches.Ifoneswitchiscalled'a,'theotherswitchiscalled'b,'andtheceilinglightiscalled'c,'thenthislittlechartdescribescompletelyandexactlyhowtheequipmentinthatroomoperates.Theonlywaytogetthatlightoffistohavebothswitch'a'andswitch'b'on.
SIMPLEVARIATIONS
Asmentioned,thisgateistheonlythingyouneedtobuildacomputer,butyouneedalotofthem,andtheyhavetobewiredtogetherinanintelligentmannerinordertobeabletomakethemdosomethinguseful.Whatwearegoingtodohereistoshowtwosimplethingsthataredonemanytimesinsideanycomputer.
Thisfirstoneisverysimple.Takethegateabove,andtakethetwoinputwires,'a'and'b,'andtiethemtogether.Thus'a'and'b'willalwaysbethesame.Theycanstillbechangedonandoff,but'a'and'b'canneverbedifferent.'A'and'b'caneitherbothbeon,orbothbeoff.Thusthechartofthiscombinationonlyhastwolinesonit,twopossibilities:
Actually,sincecolumns'a'and'b'arethesame,thereisreallyonlyoneinputanditcanbedrawnsimplylikethiswithatriangleinsteadofthe'D'shape.Itschartisalsoverysimple:
Foroursecondvariation,letscombineoneofouroriginaltypeofgatewiththenewgatethatwejustinvented,likethis:
Andwe'llcombinethechartsofhowtheywork.The'a,''b'and'x'arelikethefirstgate,the'x'and'c'arelikethesecondgate.
Thiscombinationisusedsoofteninsidecomputers,thatitisbuiltasasingleunit,andthe'x'bitisnotavailabletoconnectto.Sotomakeitsimplertounderstand,itisdrawnasasingleunitlikethis:
Theonlydifferencebetweenthispictureandthepictureofouroriginalgateisthatthelittlecircleafterthebig'D'ismissing.
Since'x'isnotused,thechartcanalsobesimplified,anditlookslikethis:
Theonlydifferencebetweenthischartandthechartofouroriginalgateisthateveryitemincolumn'c'istheoppositeofwhatitwasintheoriginalchart.
Imaginethatthiscombinationofgateswasinstalledinthatroomwiththetwolightswitchesandtheceilinglight.Theonlywaythelightcouldbeonisifbothswitcheswereon.Soifyouwalkedinthereandsawthelighton,andthenlookedattheswitches,youwouldseethattheywerebothon.Nomatterwhichswitchyoudecidedwasforthelight,andyouswitcheditoff,thelightwouldgooff.Youmightnotnoticethatifyouturnedbothoff,andthenwantedtoturnthelightbackon,youwouldn'tbeabletodoitbyjustflippingoneswitch.Youwouldhavetogothroughthesameexperiment,flippingbothswitchesuntilthelightcameon,andyouwouldfindthatoneswitchandtheotherswitchwouldhavetobeontogetthelighttolight.
Thiscombinationgatecouldbedescribedthisway:Fortheoutputtobeon,oneinputANDtheotherinputmustbothbeon.Thusthistypeofgatehasaname,andinthetraditionoftheinformalterminologyinventedbycomputerpeople,becauseitremindsusofwhatthewordANDmeans,itissimplycalledan"ANDgate."
Nowtofillinafewdetailspurposelyleftoutabove,theoriginalgatewelookedatworksliketheANDgateexcepttheoutputistheopposite,orthenegativeoftheANDgate.ThusitiscalledaNegativeANDgate,orjusta"NANDgate"forshort.
Thesimplegatethathadbothinputstiedtogetheralsohasitsownname.Theoutputisalwaystheoppositeoftheoneinput,thatis,iftheinputison,theoutputisnoton(off.)Iftheinputisoff,theoutputisnotoff(on.)TheoutputisalwaysNOTwhattheinputis,thus,itiscalleda"NOTgate."
NoticethedifferencebetweenthediagramsoftheANDgateandtheNAND
gate.TheyarethesameexceptthatthereisalittlecircleatthebeginningoftheoutputoftheNANDgate.Thethingthatlookslikealargeletter'D'meanstodotheAND'function,whichmeanstotakeactiononlyifbothinputsareon,andthelittlecirclemeansswitchtotheopposite.SoanANDgateisonifbothinputsareon,aNANDgateisoffifbothinputsareon.TheNOTgatestartswithatriangle,whichjustmeanstaketheinputandturnitintoanoutput.Thecirclethenmeanstoswitchtotheopposite.
TheANDgateisusedalotincomputers,anditisprobablytheeasiesttounderstand,butwelookedattheNANDgatefirstfortworeasons.ThefirstandlessimportantreasonisthattheNANDgateistheeasiestgatetobuild.Whenyouhavetobuildalargenumberofgates,itwillbecheaperandmorereliableifyoucanusethetypeofgatethatiseasiesttobuild.
Thesecond,andveryimportantreasonthatwelookedattheNANDgatefirstisthis:Thateverythinginacomputerthatmakesitacomputer,canbemadeoutofoneormoreNANDgates.WehavealreadyseenthattheNOTgateandtheANDgatecanbemadeoutofNANDgates,andwewillseeafewmoreinterestingcombinationsaswegoalong.ButeveryoneofthemisbasedonthissillylittlethingcalledaNANDgate.
TheprobleminthischapterhasbeenthattheNANDgateisthebasicbuildingblockofcomputers,buttheANDgateisthefirstgatethathasanamethatmakessense.SowelookedfirstattheNANDgateandtheNOTgatewithoutgivingthemnames.ThenwebuiltanANDgate,gaveititsname,andwentbackandnamedthefirsttwo.
Asanoteonthelanguagehere,theword'and'isaconjunctioninregularEnglish.Itconnectstwothings,asin"Ilikepeasandcarrots."Incomputers,weusethewordintwonewways.First,itisanadjective,awordthatmodifiesanoun.Whenwesay"thisisanANDgate,"theword"gate"isanoun,andtheword"AND"tellsuswhatkindofagateitis.Thisishow"AND"hasbeenusedinthischapter."AND"willalsobeusedasaverb,asin"letusANDthesetwobits."WewillseeANDusedinthiswaylaterinthebook.
Sobacktothesimplicitythemeofthisbook,wehavesaidthatthereisonlyonethingincomputers,bits.Andnowweseethatbitsareconstructedusinggates,andallgatescomedowntotheNANDgate.Soallyouhavetoknowtounderstandcomputersisthisverysimpledevice,theNANDgate.Nokidding!Canyouunderstandthisthing?Thenyoucanunderstandthewholecomputer.
DIAGRAMS
Ifyouwanttoseehowamechanicalmachineworks,thebestwaytodoitistolookinsideofit,watchthepartsmoveasitoperates,disassembleit,etc.Thesecondbestwayistostudyitfromabookthathasalotofpicturesshowingthepartsandhowtheyinteract.
Acomputerisalsoamachine,buttheonlythingthatmovesinsideofitistheinvisibleandsilentelectricity.Itisveryboringtowatchtheinsideofacomputer,itdoesn'tlooklikeanythingishappeningatall.
Theactualconstructionoftheindividualpartsofacomputerisaveryinterestingsubject,butwearenotgoingtocoveritanyfurtherthantosaythefollowing:Thetechniquestartswithathincrystalwafer,andinaseriesofsteps,itissubjectedtovariouschemicals,photographicprocesses,heatandvaporizedmetal.Theresultissomethingcalleda'chip,'whichhasmillionsofelectronicpartsconstructedonitssurface.Theprocessincludesconnectingthepartsintogates,andconnectingthegatesintocompletecomputersections.Thechipisthenencasedinapieceofplasticthathaspinscomingoutofit.Severalofthesearepluggedintoaboard,andthereyouhaveacomputer.Thecomputerwearegoingto'build'inthisbookcouldeasilyfitononechiplessthanaquarterofaninchsquare.
Butthepointis,thatunlikeamechanicalmachine,theactualstructureofachipisveryclutteredandhardtofollow,andyoucan'tseetheelectricityanyway.Thediagramswesawinthepreviouschapterarethebestwaytoshowhowacomputerworks,sowe'dbettergetprettygoodatreadingthem.
Throughouttherestofthisbook,wearegoingtobuildnewpartsbyconnectingseveralgatestogether.Wewilldescribewhatthenewpartdoes,andthengiveitanameanditsownsymbol.Thenwemayconnectseveralofthosenewpartsintosomethingelsethatalsogetsanameandasymbol.Beforeyouknowit,wewillhaveassembledacompletecomputer.
Everytimethereisanewdiagram,thetextwillexplainwhatitspurposeis,andhowthepartsachieveit,butthereaderreallymustlookthediagramoveruntilitcanbeseenthatthegatesactuallydowhatthebooksaystheywilldo.Ifthisisdonefaithfullywitheachone,youwillveryshortlyseeexactlyhowacomputerworks.
Thereareonlytwothingsinourdrawings,therearepartsthathaveinputsand
outputs,andtherearelines,orwires,thatconnectoutputsandinputstogether.
Whenelectricitycomesoutoftheoutputofagate,theelectricitytravelsthroughthewholewireasfastasitcango.Iftheoutputofagateison,thentheelectricityisoninthewirethatisconnectedtoit,forasfarasitgoes.Iftheoutputofagateisoff,thewholewireisoff.Iguessyoucouldconsiderthatthebitthatcomesoutofthegateincludesthewholewireaswell.
Theinputsofgatesdonotuseuptheelectricityinthewire,sooneoutputmaybeconnectedtotheinputofoneormanygates.
Whenwiresareconnectedtogether,thisisshownbyadotwheretheymeetonthediagram,andallwiresthatareconnectedtogethergetelectricityasiftheywereonewire.Whenwirescrossonadiagramwithoutadot,itmeansthatthereisnoconnectionbetweenthem,theyarenottouching,thetwobitsareseparate.
Wheneverthereisachoice,thediagramswillshowthepathoftheelectricitymovingfromlefttoright,orfromthetopofthepagetowardsthebottom.However,therewillbemanyexceptionstothis,especiallylateroninthebook.Butyoucanalwaystellwhichwaytheelectricityismovinginawirebystartingatanoutputandfollowingittoaninput.
Mostofthediagramsinthebookareveryeasytofollow.Inafewcases,therewillalsobeoneofthosechartsthatshowswhattheoutputwillbeforeverypossiblecombinationofinputs.Ifyouhavetroublefollowingadiagram,youcanpencilintheonsandoffsrightonthepage,orplacecoinsonthepageandflipthemsothatheadsmeansonandtailsmeansoff.
Unfortunately,thediagraminthenextchapterisprobablythehardestonetofollowinthewholebook,butonceyoumasterit,you'llbeanexpertdiagramreader.
REMEMBERWHEN
Youhaveprobablyheardofcomputermemory,andnowwearegoingtoseeexactlywhatthatis.Sincetheonlythinginsideofcomputersisbits,andtheonlythingthathappenstobitsisthattheyeitherturnonorturnoff,thenitfollowsthattheonlythingacomputercan'remember'iswhetherabitwasonoroff.Wewillnowseehowthatisaccomplished.
Thefollowingdiagramshowsonebitofcomputermemory.Ithappenstobeoneoftheneatesttricksyoucandowithafewgates.Wewillexaminehowitworkshereatgreatlength,andafterweunderstandit,wewillreplaceitwithitsownsymbol,anduseitasabuildingblockforbiggerandbetterthings.
ItismadeofonlyfourNANDgates,butitswiringiskindofspecial.Hereitis:
Thiscombinationasawholehastwoinputsandoneoutput."I'iswhereweinputthebitthatwewanttoremember,and'o'istheoutputoftherememberedbit.'S'isaninputthattellsthesegateswhento'set'thememory.Therearealsothreeinternalwireslabeled'a','b'and'c'thatwewillhavetolookattoseehowthesepartsworktogether.Trytofollowthiscarefully,onceyouseethatitworks,youwillunderstandoneofthemostimportantandmostcommonlyusedthingsinacomputer.
Toseehowthisworks,startwith's'onand'i'off.Since'i'and's'gointogate1,oneinputisoff,so'a'willbeon.Since'a'and's'gotogate2,bothinputsareon,andtherefore'b'willbeoff.Lookingatgate4,since'b'isoff,theoutputofgate4,'c'willbeon.Since'c'and'a'arebothon,theoutputofgate3,'0'willbeoff.'O'goesbackdowntogate4providingasecondoffinput,leaving'c'stillon.Theimportantthingtonotehereisthatwith's'on,'0'endsupthesameas'i.'
Nowwith's'stillon,letschange'i'toon.Since'i'and's'gointogate1,'a'willbeoff.'A'goestoonesideofbothgate2andgate3,thereforetheiroutputs'0'and
'b'mustbothbeon.'O'and'b'bothongointogate4andturn'c'off,whichgoesbackuptogate3providingitwithasecondoffinput,leaving'0'stillon.Theimportantthingtonotehereisthesamethingwenotedinthepreviousparagraph-thatwith's'on,'0'endsupthesameas'i.'
Sofar,wehaveseenthatwhen's'ison,youcanchange'i'onandoff,and'0'willchangewithit.'O'willgoonandoffjustthesameas'i.'With's'on,thiscombinationisnomoreusefulthanawireconnecting'i'to'0.'
Nowlet'sseewhathappenswhenweturn's'off.Lookatgate1.When's'isoff,'a'willbeonnomatterwhatyoudoto'i.'Nowyoucanswitch'i'onandoffandnothingwillhappen.Thesamegoesforgate2.'A'maybeon,but's'isoff,so'b'canonlybeon.Both'a'and'b'areon,andchanging'i'doesnothing.Nowtheonlythingleftthatmatters,thebigquestionis,whatwill'0'be?
If'i'and'0'wereonbefore's'gotturnedoff,gate3hadbothinputsoff,andgate4hadbothinputson.When's'goesoff,'a'comeson,whichisoneinputtogate3.Buttheotherinputisoff,sonothingchanges,'0'stayson.
If'i'and'0'wereoffbefore's'gotturnedoff,gate3hadbothinputson,andgate4hadbothinputsoff.When's'goesoff,'b'comeson,whichisoneinputtogate4.Buttheotherinputisoff,sonothingchanges,'c'staysonand'0'staysoff.
Sotheanswertothequestionofwhathappensto'0'when's'isturnedoff,isthatitstaysthewayitwas,anditisnolongeraffectedby'i.'
Nowwhatdowehavehere?With's'on,'0'doeswhatever'i'does.With's'off,'0'staysthewayitand'i'were,atthelastinstantjustbefore's'wentoff.Now'i'canchange,but'0'staysthewayitwas.Thiscombinationofgateslocksintheway'i'wasatanearliertime.ThisishowacombinationoffourNANDgatescan"remember."Thisisonlyonebitofmemory,butthisisthebasicbuildingblockofallcomputermemory.Allthatcomputermemoryis,isawayofpreservingthewayabitwassetatsomepointintime.
Ihopeyoufollowedthewiresandtheonsandoffsinthischapter.Onceyouseeexactlyhowthisthingworks,youwillknowthatthesesimpleNANDgatescancreateamemorybit,andIassureyouthatyouwillneverwonderaboutitagain.
Nowthatweknowhowthisthingworks,wenolongerneedtolookatthattrickyinternalwiringofthiscombination.Wehaveseenhowitworks,andfromnowon,wewilljustusethisdiagramtorepresentit:
'I'istheinputbitthatyouwanttosave.'S'istheinputthatallows'i'intothememorybitwhen's'ison,andlocksitinplaceor'sets'itwhen's'goesoff.'O'istheoutputofthecurrentorsaveddata.'M'standsforMemory.Prettysimple,eh?
Let'sgobacktoourroomwiththefunnylightswitches.IthadaNANDgatehookedupinit.Let'staketheNANDgateoutandreplaceitwiththisnewmemorybit.We'llconnecttheleftswitchtothe'i'wire,therightswitchtothe's'wire,andtheceilinglighttothe'o'wire.Wecouldstartoutwitheverythinglookingthesame,thatis,thelightison,butbothswitchesareoff.Thatwouldmeanthatatsomepointinthepast,both'i'and's'wereon,and's'gotturnedofffirst,lockingthethenstateof'i'intoourmemorybit,whichthencomesoutat'o.'Then'i'couldhavebeenswitchedoffwithoutaffectinganything.Soifwewalkedinanddecidedthatwewantedtoturnthelightoff,wewouldfirsttrythe'i'switch,turnitonandoff,andnothingwouldhappen.Thenwewouldtrythe's'switch.Whenweturniton,thelightwouldgooff.Ahawesay,the's'switchcontrolsthelight,butitisinstalledup-side-down!Sothenweturnthe's'switchbackoff,expectingthelighttocomebackon,butthelightremainsoff.Nowtheswitchesareinthesamepositionastheywerewhenweenteredtheroom,they'rebothoff,butnowthelightisoffaswell,boyisthisconfusing.NowIdon'twanttospeculateonhowmuchcursingwouldgoonbeforesomeonefiguredthisout,butintheendtheywouldfindthatwhen's'wason,thelightwentonandoffwith'i,'andwhen's'wasoff,thelightwouldstaythewayitwasjustbefore's'gotturnedoff.
WHATCANWEDOWITHABIT?
Nowwehavedescribedabit,wehaveshownhowtobuildone,howtorememberovertimewhatstateabitwasinatanearlierinstantintime,nowwhat?Whatdowedowithit?
Sinceabitisactuallynothingmorethantheelectricitybeingonoroff,theonlyactual,realthingwecandowithabitistoturnlightsonoroff,ortoastersorwhatever.
Butwecanalsouseabittorepresentsomethingelseinourlives.Wecantakeabit,andconnectittoaredlight,andsaythatwhenthisbitison,itmeansstop,andwhenthisbitisoff,youmaygo.Orifaparticularbitison,youwantfrieswithyourburger;ifitisoff,youwanttheburgeronly.
Thisistheactionofusingacode.Whatisacode?Acodeissomethingthattellsyouwhatsomethingelsemeans.Whensomethingissupposedtomeansomething,somewheresomeonehastomakealistofallofthestatesofthe'thing,'andthemeaningsassociatedwitheachofthosestates.Whenitcomestoabit,sinceitonlycanbeintwodifferentstates,thenabitcanonlymeanoneoftwothings.Acodeforabitwouldonlyneedtwomeanings,andoneofthosemeaningswouldbeassociatedwiththebitbeingoff,andtheothermeaningwouldbeassociatedwiththebitbeingon.
Thisishowyouassignmeaningtoabit.Thebitdoesnotcontainanymeaninginandofitself;thereisnoroominabitforanythingotherthanthepresenceorabsenceofelectricity.Meaningisassignedtoabitbysomethingexternaltothebit.ThereisnothingabouttrafficorFrenchfriesinabit,wearejustsayingthatforthisbitinthisplace,connectedtoaredlighthangingoveranintersection,whenitison,youmuststop,whenitisoff,youmaygo.Anotherbit,inacashregisterinafastfoodrestaurant,meansputfriesinthebagwhenthebitison,ornofrieswhenitisoff.
Thesearetwocasesofsomeoneinventingasimpletwo-itemcode.Inonecase,thecodeis:bitonmeansfries,bitoffmeansnofries,intheothercase,bitoffmeansgo,bitonmeansstop.Thesetwobitsarethesame,theyarejustusedfordifferentpurposes,andsomeonedecideswhatthemeaningofthesetwobitswillbe.Thecodeiswrittendownsomewhereinthelawbooks,orintherestaurantmanager'shandbook,butthecodeisnotinthebit.Thestateofthebitmerelytellssomeonewhichlineofthecodetheyaresupposedtobelieveistrueatthecurrentmoment.That'swhatacodeis.
Likethespieswhopassmessagesbyusingasecretcode,themessagemaybeseenbyotherpeople,butthoseotherpeopledon'thavethecode,sotheydon'tknowwhatthemessagemeans.Maybeonespyhasaflowerpotsittingonthesillinthefrontwindowofhisapartment.Whenthepotisontheleftsideofthesill,itmeans"Meetmeatthetrainstationat1:30."Andwhentheflowerpotisontherightsideofthesill,itmeans"Nomeetingtoday."Everyday,theotherspywalksdownthestreetandglancesupatthatwindowtoseewhetherheneedstogotothetrainstationtoday.Everyoneelsewhowalksdownthatstreetcanjustaseasilyseethismessage,buttheydon'thavethecode,soitmeansnothingtothem.Thenwhenthetwospiesdomeet,theycanpassapieceofpaperthatiswritteninanothersecretcode.Theyencodeanddecodethemessageusingacodebookthattheydonotcarrywhentheymeet.Soiftheirmessageisinterceptedbyanyoneelse,itwon'tmeananythingtothatsomeoneelse.Someonewhodoesn'thavethecodebookwon'thavethepropermeaningsforthesymbolsonthesheetofpaper.
Acomputerbitisstill,andwillalwaysbe,nothingmorethanaplacewherethereisorisnotelectricity,butwhenwe,asasocietyofhumanbeings,useabitforacertainpurpose,wegivemeaningtothebit.Whenweconnectabittoaredlightandhangitoveranintersection,andmakepeoplestudydriver'shandbooksbeforegivingthemdriver'slicenses,wehavegivenmeaningtothatbit.Redmeans'stop,'notbecausethebitiscapableofdoinganythingtoavehicletravelingontheroad,butbecauseweaspeopleagreethatredmeansstop,andwe,seeingthatbiton,willstopourcarinordertoavoidbeinghitbyacartravelingonthecrossstreet,andwehopethateveryoneelsewilldothesamesothatwemaybeassuredthatnoonewillhituswhenitisourturntocrosstheintersection.
Sotherearemanythingsthatcanbedonewithabit.Itcanindicatetrueorfalse,goorstop.Asingleyesornocanbeamajorthing,asintheanswerto"Willyoumarryme?"oraneverydaymattersuchas"Wouldyoulikefrieswiththat?"
Butstill,therearemanythingsthatcannotbedonewithabit,orseemtobeincompatiblewiththeideaofbitsaltogether.Therecanbemanyexamplesofyes/nothingsineverydaylife,buttherearemanymorethingsthatarenotasimpleyesorno.
Inthecaseofthetelegraph,whichwasindisputablyjustonebit,howcantherebemorethantwoitemsintheMorsecode?Theansweristhattheabilitytosendandreceivemessagesdependedontheskillsandthememoriesoftheoperatorsatbothendsofthewire.IntheMorseCode,ifthekeywaspressedforavery
shorttime,thatwascalleda"dot(.),"andifitwaspressedforaslightlylongertime,thatwascalleda"dash(-)."Eachletterofthealphabetwasassignedauniquecombinationofdotsandordashes,andbothoperatorsstudiedthecode,memorizeditandpracticedusingit.Forinstance,thecodefortheletter'N'wasdashdot(-.)andthecodefortheletter'Cwasdashdotdashdot(-.-.).Thelengthoftheontimesweredifferenttomakedotsanddashes,andthelengthsoftheofftimesweredifferenttodistinguishbetweenthetimethatseparatesdotsanddasheswithinaletter,thetimethatseparatesletters,andthetimethatseparateswords.Youneedalongerofftimetokeepfromconfusinga'Cwithtwo'N's.Thereceivingpersonhadtorecognizetheseaspatterns-thatis,hehadtohearandrememberthelengthsofseveralonandofftimesuntilherecognizedaletter.Thetelegraphapparatusdidn'thaveanymemoryatall,therewasneverevenonewholeletteronthewireatanyonetime,thepiecesofletterswentdownthewire,tobeassembledintodotsanddashesinthemindoftheoperator,thenintoletters,andthenintowordsandsentenceswrittenonasheetofpaper.Sothetelegraphbitachievesmorethantwomeaningsbyhavingseveralindividualtimeswhentheremaybeonsoroffs.
IfacomputerwerebuiltontheprinciplesoftheMorsecode,itwouldjusthavealightbulbontopofitflashingthecodeatus.Sincewe'dratherseewholeletters,wordsandsentencesonthescreensimultaneously,weneedsomethingmorethanasinglebitandthisoldcode.
Evenintheexamplesusedinthischapter,realtrafficlightsactuallyhavethreebits,oneforred,oneforyellowandoneforgreen.Ifyouhadonlyonebit,youcouldjusthavearedlightattheintersection,andwhenitwasonthatwouldmeanstop,andwhenitwasoffthatwouldmeango.Butwhenitwasoff,youmightwonderwhetheritwasreallyoff,orwhetherthebulbhadjustburnedout.Sousingthreebitsisalotmoreusefulinthiscase.
Intherealworld,wehavealreadyseenthatcomputerscancontainletters,words,sentences,entirebooks,aswellasnumbers,pictures,soundsandmore.Andyet,allofthisdoescomedowntonothingmorethanbits.
Ifwewantourcomputermemorytobeabletoholdmorethananonoroff,oryesorno,wewillhavetohavesomethingmorethanjustonebit.Fortunately,wecandosomethingmuchmoreusefuljustbyusingseveralbitstogether,andthenmakingupacode(ormaybeseveralcodes)toassignsomeusefulmeaningtothem.
AROSEBYANYOTHERNAME
Beforewegoon,wearegoingtointroduceachangetowhatwecallsomething.Asweknow,allofthebitsinthecomputerareplaceswherethereisorisnot,someelectricity.Wecallthesestates,"on"and"off,"andthatisexactlywhattheyare.Eventhoughtheseareshortwords,thereareplaceswhereitisaloteasier,clearerandsimplertouseasinglesymboltodescribethesestates.Fortunately,we'renotgoingtoinventanythingtricky,we'rejustgoingtousetwosymbolsyoualreadyknowwell,thenumberszeroandone.Fromhereonout,wewillcalloffo,andwewillcallon1.Andsometimeswewillstilluseonandoff.
ThusthechartforourNANDgatewilllooklikethis:
Thisisveryeasytounderstand,ofcourse,butthepointthatneedstobemadehere,isthatthecomputerpartshavenotchanged,theonlythingthathaschangediswhatwe,aspeoplelookingatthemachine,arecallingit.Justbecausewecallabitazeroorone,thatdoesn'tmeanthatsuddenlynumbershaveappearedandarerunningaroundinsidethecomputer.Therearestillnonumbers(orwordsorsoundsorpictures)inacomputer,onlybits,exactlyaspreviouslydescribed.Wecouldhavecalledthemplusandminus,yesandno,trueandfalse,headsandtails,somethingandnothing,northandsouth,orevenBertandErnie.Butzeroandonewilldoit.Thisisajustasimple,twoitemcode.Onmeansl,andoffmeans0.
Asacommenthere,thereseemstobeatrendamongtheappliancemanufacturersoftheworldtoreplacetheobsoleteandold-fashionedtermsofonandoffwiththemodern0and1.Onmanypowerswitchestheyputaobytheoffposition,anda1bytheonposition.ThefirstplaceIsawthiswasona
personalcomputer,andIthoughtthatitwasacutenovelty,beingonacomputer,butnowthispracticehasspreadtocellphones,coffeemakersandautomobiledashboards.ButIthinkthatthisisamistake.Doyouunderstandthatthecodecouldjustaseasilyhavebeendefinedas"offmeans1andonmeans0?"Thecomputerwouldworkexactlythesameway,onlytheprintinginthetechnicalmanualsthatdescribewhatishappeninginsidethecomputerwouldchange.
Whenyouseeoneoftheseo/1switches,youhavetotranslateitbackfromthisverycommonlyusedcomputercodeintowhatitreallymeans,onoroff.Sowhybother?Youdon'twanttoturnyourcoffeemachine'1',youwantthepowerONsoyoucangetyourJavaandwakeupalready.Imagineputtingthesesymbolsonawafflemakerbackin1935.Nobodywouldhavehadanyideaofwhatitmeant.Itisprobablyjustsothatmanufacturersdon'thavetohaveswitchesprintedindifferentlanguages.Ormaybethistrendcomesfromanaltruisticdesiretoeducatethepublicintothemodern'fact'thata1isthesameason,butitisn'tafact,it'sanarbitrarycode.
EIGHTISENOUGH
Inordertobeabletorepresentsomethingmorethansimpleyes/nomatters,whatwearegoingtodoistostackupeightbitsinasinglepackage,andusethemasasingleunit.Hereisadiagramofhowitisdone.Wehavetakeneightofourmemorybits,eachonestillhasitsowndatainput'i'anditsownoutput'o,'butwehavewiredalleightofthesetinputs's'together.Thuswhenthesingle's'getsturnedonandthenoffagain,alleightofthese'M'swillcapturethestatesoftheircorresponding'i'satthesametime.Thepictureontheleftshowsalleight'M's,theoneontherightisthesamething,justalittlesimpler.
Thisassemblyhasaname;itiscalledabyte,thusthe"B"inthediagram.Thereareseveralconflictingexplanationsofexactlywherethiswordcamefrom,butsinceitsoundsjustliketheword"bite,"youcanjustthinkofitasawholemouthfulcomparedwithasmallerunit,abit.Justtoshowyouthatcomputerdesignersdohaveasenseofhumor,whentheyusefourbitsasaunit,theycallitanibble.Soyoucaneatatinybitofcherrypie,orhaveanibbleortakeawholebyte.
Whenwehadabit,wewouldjustsaythatitsstatewaseitheroor1.Nowthatwehaveabyte,wewillwritethecontentsofthebytelikethis:00000000,and
youcanseewhyweswitchedfromusingoff/onto0/1.Thatshowsthecontentsofeachoftheeightbits,inthiscasetheyareallzeros.Thespaceinthemiddleisjusttheretomakeitalittleeasiertoread.Thelefthandoor1wouldcorrespondtothetopbitinourbyte,andtherightmostoor1wouldrepresentthebottombit.
Asyouhadbetterknowbynow,abithastwopossiblestatesthatitcanbein—onoroff.Ifyouhavetwobits,therearefourpossiblestatesthatthosetwobitscanbein.DoyourememberthechartwedrewfortheinputsoftheNANDgate?Therewerefourlinesonthechart,oneforeachpossiblecombinationofthetwoinputbitstothegate,0-0,0-1,1-0and1-1.
Noticethattheorderofthebitsdoesmatter-thatis,ifyoulookattwobitsandonlyaskhowmanybitsareon,thereareonlythreepossibilities:nobitson,onebitonortwobitson.Thatwouldbecallingthe1-0and0-1combinationsthesamething.Forthepurposeofusingmultiplebitstoimplementacode,wedefinitelycareabouttheorderofthebitsinabyte.Whentherearetwobits,wewanttouseallfourpossibilities,sowehavetokeepthebitsinorder.
Howmanydifferentpossibilitiesaretherewhenyouuseeightbits?Ifallyouhaveisonebit,itcanbeinoneoftwostates.Ifyouaddasecondbit,thepairhastwiceasmanystatesasbeforebecausetheoldbithasitstwostateswhilethenewbitisoneway,andthentheoldbithasitstwostateswhilethenewbitistheotherway.Sotwobitshavefourstates.Whenyouaddathirdbit,thefirsttwohavefourstateswiththenewbitoffandfourstateswiththenewbiton,foratotalofeightstates.Everytimeyouaddabit,youjustdoublethenumberofpossiblestates.Fourbitshave16states,fivehave32,sixhave64,sevenhave128,eighthave256,ninehave512states,andsoon.
Wearegoingtotakeeightbits,andcallitabyte.Sinceabitisathingthathasalocationinspace,thatcanbeinoneoftwostates,thenabyteisathingthathaseightseparatelocationsinspace,eachofwhichcanbeonoroff,thatarekeptinthesameorder.Thebyte,takenasawhole,isalocationinspacethatcanbeinanyoneof256statesatanygiventime,andmaybemadetochangeitsstateovertime.
CODES
Abitcouldonlyrepresentyes/notypesofthings,butnowthatwehave256possibilities,wecanlookforthingsinourlivesthatareslightlymorecomplicated.
Oneofthefirstthingsthatmightfitthebilliswrittenlanguage.Ifyoulookinabookandseeallofthedifferenttypesofsymbolsthatareusedtoprintthebook,youwillseeall26lettersofthealphabetinuppercaseaswellaslowercase.Thentherearethenumbersothrough9,andtherearepunctuationmarkslikeperiods,commas,quotes,questionmarks,parenthesesandseveralothers.Thentherearespecialsymbolslikethe'at'sign(@,)currency($,)andmore.Ifyouaddtheseup,52letters,10numbers,afewdozenforpunctuationandsymbols,yougetsomethinglike100differentsymbolsthatmayappearprintedonthepagesoftheaveragebook.
Fromhereonout,wewillusetheword'character'tomeanoneofthissortofthing,oneoftheletters,numbers,orothersymbolsthatareusedinwrittenlanguage.Acharactercanbeeitheraletter,anumber,apunctuationmarkoranyothertypeofsymbol.
Sowehavewrittenlanguagewithabout100differentcharacters,andourbytewith256possibilities,maybewecanrepresentlanguagewithbytes.Letssee,howdoyouputan'A'intoabyte?Thereisnothinginherentinabytethatwouldassociateitwithacharacter,andthereisnothinginherentinacharacterthathasanythingtodowithbitsorbytes.Thebytedoesn'tholdshapesorpictures.Dividingacharacterintoeightpartsdoesnotfindanybits.
Theanswer,asbefore,istouseacodetoassociateoneofthepossiblestatesofthebytewithsomethingthatexistsintherealworld.TheletterA'willberepresentedbyaparticularpatternof1sand0sinthebitsofabyte.Thebytehas256differentpossiblestates,sosomeoneneedstositdownwithpencilandpaperandlistoutall256ofthosecombinations,andnexttoeachone,putoneofthecharactersthathewantsthatpatterntorepresent.Ofcourse,bythetimehegetstothe101stlineorso,he'llrunoutofcharacters,sohecanaddeverytypeofrarelyusedsymbolhecanthinkof,orhecanjustsaythattherestofthecombinationswillhavenomeaningasfaraswrittenlanguageisconcerned.
Andso,intheearlydaysofcomputers,eachmanufacturersatdownandinventedacodetorepresentwrittenlanguage.Atsomepoint,thedifferentcompaniesrealizedthatitwouldbebeneficialiftheyallusedthesamecode,in
casetheyeverwantedtheircompany'scomputerstobeabletocommunicatewithanotherbrand.Sotheyformedcommittees,heldmeetingsanddidwhateverelsetheyneededtodotocomeupwithacodethattheycouldallagreeon.
Thereareseveralversionsofthiscodedesignedfordifferentpurposes,andtheystillholdmeetingstodaytoworkoutagreementsonvariousesotericdetailsofthings.Butwedon'tneedtoconcernourselveswithallthattoseehowacomputerworks.Thebasiccodetheycameupwithisstillinusetoday,andIdon'tknowofanyreasonwhyitwouldeverneedtobechanged.
Thecodehasaname,itisthe:AmericanStandardCodeforInformationInterchange.ThisisusuallyabbreviatedtoASCII,pronounced"aass-key."Wedon'tneedtoprintthewholecodehere,buthere'sasample.Theseare20ofthecodesthattheycameupwith,thefirst10lettersofthealphabetinuppercaseandlowercase:
Eachcodeisunique.It'sinterestingtonotethewaythattheyarrangedthecodessothatthecodesforuppercaseandlowercaseofthesameletterusethesamecodeexceptforonebit.Thethirdbitfromtheleftisoffforalluppercaseletters,andonforalllowercaseletters.
Ifyouwantedtoputamessageonyourcomputerscreenthatsaid"HelloJoe"youwouldneedninebytes.Thefirstbytewouldhavethecodeforuppercase"H",thesecondbytewouldhavethecodeforlowercase"e",thethirdandfourthbyteswouldhavethecodeforlowercase"1",thefifthbytewouldhavethecodeforlowercase"o",thesixthbytewouldhavethecodeforablankspace,andbytesseven,eightandninewouldcontainthecodesfor"J","o"and"e."
Noticethatthereisevenacodeforablankspace(itis00100000bytheway.)Youmaywonderwhythereneedstobeacodeforablankspace,butthatjustgoestoshowyouhowdumbcomputersare.Theydon'treallycontainsentencesorwords,therearejustanumberofbytessetwiththecodesfromtheASCIIcodetablethatrepresenttheindividualsymbolsthatweuseinwrittenlanguage.Andoneofthose"symbols,"isthelackofanysymbol,calledaspace,thatweusetoseparatewords.Thatspacetellsus,thereader,thatthisistheendofonewordandthebeginningofanother.Thecomputeronlyhasbytes,eachofwhichcanbeinoneofits256states.Whichstateabyteiscurrentlyin,meansnothingtothecomputer.
Soletustakeamemorybyte,andsetthebitsto01000101.ThatmeansthatwehaveputtheletterEintothebyte,right?Well...notreally.WehavesetthepatternthatappearsnexttotheletterEintheASCIIcodetable,butthereisnothinginherentinthebytethathastodowithan'E.'IfThomasEdisonhadbeentestingeightofhisnewexperimentallightbulbs,andhadthemsittinginarowonashelf,andthefirst,third,fourth,fifthandseventhlightbulbshadburnedout,theremaininglightbulbswouldbeabytewiththispattern.Buttherewasn'tasinglepersononthefaceoftheEarthwhowouldhavelookedatthatrowofbulbsandthoughtoftheletter'E,'becauseASCIIhadnotyetbeeninvented.Theletterisrepresentedbythecode.Theonlythinginthebyteisthecode.
Thereyouhavethesubjectofcodes.Acomputercodeissomethingthatallowsyoutoassociateeachofthe256possiblepatternsinabytewithsomethingelse.
Anotherlanguagenotehere,sometimesthewordcodereferstothewholelistofpatternsandwhattheyrepresent,asin"Thismessagewaswrittenwithasecretcode."Sometimescodejustreferstooneofthepatterns,asin"Whatcodeisinthatbyte?"Itwillbeprettyobviousfromthecontextwhichwayitisbeingused.
BACKTOTHEBYTE
Doyourememberthememorybytewedrewafewchaptersago?Itwaseightmemorybitswiththeir's'wiresallconnectedtogether.Almosteverytimethatweneedtorememberabyteinsideacomputer,wealsoneedanadditionalpartthatgetsconnectedtothebyte'soutput.ThisextrapartconsistsofeightANDgates.
TheseeightANDgates,together,arecalledan"Enabler."Thedrawingontheleftshowsalloftheparts,thedrawingontherightisasimplerwaytodrawit.
ThesecondinputofalleightANDgatesareconnectedtogetherandgiventhename'enable,'or'e'forshort.When'e'isoff,whatevercomesintotheEnablergoesnofurther,becausetheothersideofeachANDgateisoff,thustheoutputsofthosegatesareallgoingtobeoff.When'e'ison,theinputsgothroughtheEnablerunchangedtotheoutputs,'o.'
Bytheway,whengatesareusedforsomethinglikethis,thename"gate"startstomakesomesense.AnEnablerallowsabytethroughwhenthebit'e'islandstopsthebytewhenitiso.So'e'beingonislikeopeningagate,and'e'beingoffislikeclosingagate.
Wewilltakeourbyte,andconnectittoanenabler,asshowninthelefthanddrawing.Tosimplifyonceagain,wecandrawitasshownontheright.
Nowwehaveacombinationthatcanstoreeightbits.Itcapturesthemallatthesametime,anditcaneitherkeepthemtoitself,orletthemoutforusesomewhereelse.ThiscombinationofaByteandanEnabler,hasaname,itiscalledaRegister,thusthe'R'inthedrawing.
Therewillbeafewplacesinthisbookwherethereareregistersthatneverneedtohavetheiroutputsturnedoff.Inthosecases,wewilldrawaregisterthatonlyhasa'set'bit,andno'enable'bit.Weshouldprobablyrefertothesedevicesas'bytes,'butwewillcallthemregistersnonetheless.
Registersimplymeansaplacetorecordsomekindofinformation,likeahotelregisterwherealltheguestssignin,oracheckregisterwhereyouwritedowneachcheckthatiswritten.Inthecaseofthiscomputerpart,yourecordthestateoftheeightinputbits.Thisregisterisverylimitedthough,inthatitcanonlyholdonesetofvalues;inahotelregisterthereisanewlineforeachguest.Everytimeyoustoreanewstateinacomputerregister,thepreviousstateoftheeightmemorybitsislost.Theonlythingthatisinthereisthemostrecentlysavedvalue.
THEMAGICBUS
Therearemanyplacesinacomputerwhereeightwiresareneededtoconnectregisterstogether.Ourregister,forexample,haseightmemorybits,eachofwhichhaveaninputandanoutput.Tosimplifyourdiagrams,wewillreplaceoureightwireswithadoubleline.
Soourregistercanlooklikeoneofthese:
Or,wecansimplify,andreplaceitwithoneofthese:
It'sexactlythesamething,wewilljustsavealotofinkinourdrawings,andtheywillbeeasiertounderstand.
Whenthereisaconnectionbetweentwoofthesebundlesofwires,onewireofeachbundleisconnectedtoonewireoftheotherbundleasshowninthediagramontheleft.Butwewillsimplifyit,andjustdrawitlikethediagramontheright.
Now,thisgroupingofeightwiresissocommoninsidecomputersthatithasaname.Itiscalledabus.Whyisitcalledabus?Well,itprobablyhastodowith
theoldelectricalterm'buss,'thatmeansabarofmetalusedasaverylargewireinplaceslikepowergeneratingplants.Butthereisalsoaninterestingsimilaritytothekindofbusthatpeopleusefortransportation.
Abusisavehiclethatcommonlytravelsalongapredeterminedroute,andmakesmanystopswherepeoplegetonoroff.Theystartsomewhere,andthebustakesthemtosomeotherplacetheyneedtobe.Intheworldofcomputers,abusissimplyasetofeightwiresthatgoestovariousplacesinsidethecomputer.Ofcourse,eightisthenumberofwiresneededtocarryabyteofinformation.Insidethecomputer,thecontentsofbytesneedtogetfromwheretheyaretootherplaces,sothebusgoestoalltheseplaces,andthedesignoftheregisterallowsthecontentsofanyselectedbytetogetontothebus,andgetoffataselecteddestination.
Inthefollowingexample,wehaveabus,andtherearefiveregisters,eachofwhichhasbothitsinputandoutputconnectedtothesamebus.
Ifallofthe‘s’bitsand‘e’bitsareoff,eachregisterwillbesetthewayitis,andwillstaythatway.IfyouwanttocopytheinformationfromR1intoR4,firstyouturnthe‘e’bitofR1on.ThedatainR1willnowbeonthebus,andavailableattheinputsofallfiveregisters.Ifyouthenbrieflyturnthe‘s’bitofR4onandbackoff,thedataonthebuswillbecapturedintoR4.Thebytehasbeencopied.Soacomputerbusisalittlelikethebusthatcarriespeople.Thereareanumberofstops,andbytescangettowheretheyneedtogo.
Noticethatwecancopyanybyteintoanyotherbyte.YoucancopyR2intoR5,orR4intoR1.Thebusworksineitherdirection.Theelectricityputonthebuswhenyouenableanyregistergoesasfastaspossibletotheinputsofeverythingelseonthebus.Youcouldevenenableoneregisterontothebusandsetitintotwoormoreotherregistersatthesametime.Theonethingyoudon’twanttodoistoenabletheoutputsoftworegistersontothebusatthesametime.
Intermsofthesizesofbits,youcouldlookatitthisway:Whenthe‘e’bitofR1getsturnedon,thebitsinR1nowgetlonger,theyareabiggerspacebecausetheyarenowconnectedtothebus,sothose8bitsnowincludeR1andtheentirebus.Whenthe'S'bitofR4getsturnedon,theR1bitsgetevenbiggerbecausetheynowincludeR1,thebusandR4.IfanythinginR1weretosomehow
changeatthistime,thebusandR4wouldimmediatelychangewithit.Whenthe's'bitofR4getsturnedoff,R4regainsitsstatusasaseparatebyte,andwhenthe'e'bitofR1turnsoff,thebusceasesbeingapartofR1.
Sothisisabus.Itisabundleofeightwiresthattypicallygoestomanyplaces.
Onemorethingaboutregisters:Therearemanyplaceswherewearegoingtoconnecttheinputandoutputofaregistertothesamebus,sotosimplifyevenfurther,wecanjustshowonebundleofwireslabeled'i/0,'meaninginputandoutput.Allofthefollowingareexactlyequivalentasfarashowtheywork.Theplacementofthewiresonthedrawingmaybeadjustedtomakeitasunclutteredaspossible.
Anotherlanguagenote:Abyteisalocationthatcanbeinoneof256states.Sometimeswetalkaboutmovingabytefromheretothere.Bydefinition,bytesdonotmovearoundinsidethecomputer.Thebyteonlyreferstothelocation,butsometimeswhensomeonewantstorefertothecurrentsettingofthebyte,andtheyoughttosay"letscopythecontentsofR1intoR4,"theysimplifyandsay"moveR1toR4"or"movethisbyteoverthere."They'reusingthewordbytetorefertothecontentsofthebyte.Again,thecontextusuallymakesthisveryclear.IntheexampleaboveofcopyingthecontentsofR1intoR4,youmayhearitdescribedas"movingabytefromR1toR4."Technically,R1andR4arethebytes,whichdonotmove,onlythecontentsgoesfromplacetoplace.
Also,thecontentsdonotleavetheplacewheretheycamefrom.Whenyouaredone"moving"abyte,the"from"bytehasnotchanged,itdoesn'tlosewhatithad.Attheotherend,thepatternthatwasoriginallyinthe"to"byteisnow"gone,"itdidn'tgoanywhere,itwasjustwrittenoverbythenewinformation.Theoldpatternsimplyceasestoexist.Thenewinformationisexactlythesameaswhatisstillinthefirstbyte.Thebytedidn'tmove,therearestilltwobytesintwolocations,buttheinformationinthefirstbytehasbeencopiedintothesecondbyte.
MOREGATECOMBINATIONS
Nowwearegoingtoshowjusttwomorecombinations,andthenwewillbeableputtogetherwhatweknowsofar,tomakethefirsthalfofacomputer.Sodon'tgetdiscouraged,justalittlefurtherandwe'llbehalfwayhome.
Thefirstcombinationisverysimple.ItisjustanANDgatewithmorethantwoinputs.IfyouconnecttwoANDgateslikethisdiagramontheleft,youseethatfor'd'tobeon,allthreeinputs,'a,''b'and'c'havetobeon.Sothiscombinationcansimplybedrawnlikethisdiagramontheright:
Andthechartthatshowshowitoperateslookslikethis:
Imaginereplacinginput'c'withanotherANDgate,thenyouwouldhaveafourinputANDgate.YoucouldthenreplaceanyofthefourinputswithanotherANDgate,andhaveafiveinputANDgate.Thiscanbedoneasmanytimesas
necessaryforwhatyouaredoing.
Asyouaddinputs,thechartwillneedmoreandmorelines.Everytimeyouaddanotherinput,youdoublethenumberofcombinationsthattheinputscanhave.ThechartwesawfortheoriginaltwoinputANDgatehadfourlines,oneforeachpossibility.Thethreeinput,directlyabove,haseightlines.AfourinputANDgatewillhave16lines,afiveinputwillhave32,etc.Inallcasesthough,foranANDgate,onlyonecombinationwillresultintheoutputturningon,thatbeingthelinewhereallinputsareon.
Hereisthelastcombinationweneedtomakethefirsthalfofacomputer.Thiscombinationisdifferentfromanythingwehavelookedatsofar,inthatithasmoreoutputsthaninputs.Ourfirstexamplehastwoinputsandfouroutputs.Itisnotverycomplicated,itjusthastwoNOTgatesandfourANDgates.
Inthediagrambelow,'a'and'b'aretheinputscominginfromtheleft.BothofthemareconnectedtoNOTgates.TheNOTgatesgeneratetheoppositeoftheirinputs.Therearefourverticalwiresgoingdownthepagethatcomefrom'a'and'b'andtheoppositesof'a'and'b.'Thus,foreach'a'and'b,'therearetwowiresgoingdownthepage,whereoneofthemwillbeonifitsinputison,andtheotherwillbeonifitsinputisoff.NowweputfourANDgatesontheright,andconnecteachonetoadifferentpairoftheverticalwiressuchthateachANDgatewillturnonforadifferentoneofthefourpossiblecombinationsof'a'and'b.'ThetopANDgate,labeled"0/0"isconnectedtothewirethatisonwhen'a'isoff,andthewirethatisonwhen'b'isoff,andthusturnsonwhen'a'and'b'arebotho.ThenextANDgate,"0/1"isconnectedtothewirethatisonwhen'a'isoff,and'b,'soitturnsonwhen'a'isoand'b'is1,etc.
Theinputscanbeoninanycombination,bothbitsoff,oneon,theotheron,orbothon.None,oneortwoon.Theoutputs,however,willalwayshaveoneandonlyoneoutputonandtheotherthreeoff.Theonewhichisonisdeterminedbythecurrentstatesof'a'and'b.'
Thiscombinationiscalledadecoder.Thenamemeansthatifyouconsiderthefourpossiblestatesofthetwoinputsasacode,thentheoutputtellsyouwhichofthecodesiscurrentlyontheinput.Maybeit’snotagreatname,butthat’swhatitmeanttosomeoneonce,andthenamestuck.Thisdecoderhastwoinputs,whichmeansthattherecanbefourcombinationsofthestatesoftheinputs,andtherearefouroutputs,onecorrespondingtoeachofthepossibleinputcombinations.
Thiscanbeextended.Ifweaddedathirdinput,therewouldthenbeeightpossibleinputcombinations,andifweusedeight,threeinputANDgates,wecouldbuildathreeinput,eightoutputdecoder.Similarly,wecouldbuildafourinput,16outputdecoder.Decodersarenamedbythenumberofinputs“X”thenumberofoutputs.Like2X4,3X8,4X16,5X32,6X64,etc.
Again,wewillsimplifyourdrawings,wewon’tshowanyoftheinternalpartsorwiring,we’lljusthaveaboxwithanameandtheinputsandoutputsthatweareinterestedin.WehaveseenhowNANDgatesmakeNOTgatesandANDgates,andthenNOTgatesandANDgatesmakeaDecoder.ItisaboxfullofNANDgateswireduptodosomethinguseful.Weknowwhatitdoes,oneandonlyoneoftheoutputsisalwayson,andwhichoneitis,isdeterminedbythestateofthethreeinputs.That’sallitdoes.
FIRSTHALFOFTHECOMPUTER
Letsbuildsomethingwiththepartswehavesofar.Actually,wecannowbuildfullyhalfofwhat'sinacomputer.
First,let'sbuildsomethingsimilaroutofwood(inourminds,)thenwe'llcomebackandshowhowtobuildacomputerversionthatdoesprettymuchthesamething.
Youknowinahotel,atthefrontdesk,onthewallbehindtheclerk,thereareaseriesoflittlewoodencubbyholes,oneforeachroominthehotel.That'swheretheykeepextraroomkeysandmessagesormailfortheguests.Oryoumayhaveseenanoldmoviewheresomeoneinanoldpostofficewassortingthemail.Hesitsatatablewithaseriesofcubbyholesattheback.Hehasapileofunsortedmailonthetable,picksuponeatatime,readstheaddress,andputstheletterintheappropriatecubbyhole.
Sowe'regoingtobuildsomecubbyholes.Ourswillbethreeinchessquare,andtherewillbesixteencubbyholeshighandsixteencubbyholesacross.That'satotalsizeoffourfeetbyfourfeet,withatotaloftwohundredfiftysixcubbies.
Nowwe'lladdsomethingthattheydon'thaveinthepostofficeorthehotel.We'regoingtoputalargewoodpanelrightinfrontofthecubbieswhichistwiceaswideasthewholething,andinthemiddleithasaverticalslotthatisjustlargeenoughtoexposeonecolumnof16cubbies.Thepanelwillhavewheelsonthebottomsoitcanslideleftandrighttoexposeanyoneoftheverticalcolumnsofsixteencubbiesatatime,andcoveralloftheothercolumns.
Let'stakeanotherwoodpaneljustlikethefirst,butturnitupsidewayssoitistwiceashighasourcubbyholes,andtheslotinthemiddlegoessidetoside.Thissecondpanelwillbemountedrightinfrontofthefirst,insomethinglikeawindowframe,soitcanslideupanddown,exposingjustonerowofsixteencubbiesatatime.
Sonowwehaveaseriesof256cubbyholes,andtwoslottedwoodenpanelsinfrontofthemthatallowonlyonecubbyatatimetobevisible.Ineachofthesecubbies,wewillplaceasingleslipofpaperonwhichwewillwriteoneofthepossiblecombinationsofeightzerosandones.
Thiscubbyholedevicehas256placestostoresomething.Atanygiventime,wecanselectoneandonlyoneofthoseplacesbyslidingthewoodpanelssidetosideorupanddown.Attheselectedcubbyhole,wecanreachinandgettheslip
ofpaperandreadit,orreplaceitwithanotherone.
Nowwewilltakethegates,registersanddecodersthatwehavedescribed,andmakesomethingoutofthemthatdoesprettymuchthesamethingasourcubbyholedevice.Thisthingwillhave256placesinwhichtostoresomething,andwewillbeabletoselectoneandonlyoneofthoseplacesatanygiventime.
Referencingthediagrambelow,westartwithasingleregister.Itsinput'a,'isabusthatcomesfromsomewhereelseinthecomputer.Acombinationofbitsisplacedonthebusandthe'sa'(seta)bitgoes1theno.Thatbitpatternisnowstoredinthisregister,whichisoneofthoseregisterswhoseoutputisalwayson.Thefirstfouroutputbitsareconnectedtoone4X16decoder,andtheotherfouroutputbitsareconnectedtoanother4X16decoder.Theoutputsofthetwodecodersarelaidoutinagridpattern.Thewiresdonottoucheachother,butthereare16by16,or256intersectionsherethatwewillmakeuseofsoon.Adecoder,asstated,hasoneandonlyoneofitsoutputsonatanytime,andtherestareoff.Sincewehavetwodecodershere,therewillbeonehorizontalgridwireon,andoneverticalgridwireon.Therefore,ofthese256intersections,therewillbeonlyoneintersectionwhereboththehorizontalandverticalwiresareon.WhichintersectionthatiswillchangeeverytimethevalueinRischanged,buttherewillalwaysbeonewherebothwiresareonwhiletheother255willhaveonlyoneonornoneon.
Atthebottomofthisdiagramisonebusandan‘s’and‘e’bit,justthesameastheconnectionsthatgotoaregister.Asyoucansee,theygoupwardsandintothegrid.Thediagramdoesn’tshowit,buttheygoupunderthegridallthewaytothetop,sothateachofthe256intersectionshasabusandan‘s’and‘e’bitnearby.
Thereisacircleonthediagramabove,aroundoneoftheintersectionsofthegrid.Whatisinthiscircleismagnifiedinthediagrambelow,showingthattherearethreeANDgatesandoneregisterateachofthe256intersections.Aswecansee,thereisanANDgate‘x,’connectedtotheoneverticalgridwireandtheonehorizontalgridwireatthisintersection.These‘x’gatesaretheonlythingsconnectedtothegrid.Therestoftheconnectionsgodowntothebusand‘s’and‘e’bitsatthebottomofthediagram.Rememberthatthereisonlyoneintersectionwherebothgridwiresareon.Therefore,thereare256ofthese‘x’gates,butonlyoneofthemhasitsoutputonatanygiventime.Theoutputofthat‘x’gategoestoonesideeachoftwomoreANDgates.Thesetwogatescontrolaccesstothesetandenableinputsoftheregisteratthatintersection.Sowhenan‘x’gateisoff,the‘s’and‘e’bitsofthatregistercannotbeturnedon.Thatwillbethecasefor255oftheseregisters,theoneswherethe'x'gateisoff.Butoneintersectionhasits'x'gateon,anditsregistercanbesetfromthebus,or
itscontentscanbeenabledontothebusandsentelsewherebyusingthe's'and'e'bitsatthebottomofthediagram.
Theaboveisthecomputer'smainmemory.Itishalfofwhatisnecessarytobuildacomputer.Itissometimescalledbydifferentnames,butthemostcorrectnamecomesfromthefactthatyoucanselectanyoneofthe256bytesonemoment,andthenyoucanimmediatelyselectanyotherofthe256bytes,anditdoesnotmatterwherethelastonewas,orwherethenextoneis,thereisnospeedadvantageordisadvantagetotheorderinwhichyouselectthebytes.Becauseofthisquality,thisisagoodtypeofmemorytouseifyouwanttobeabletoaccessthebytesofmemoryinarandomorder.Sothistypeofmemoryiscalled"RandomAccessMemory,"or"RAM"forshort.
ThisisRAM.Ituses257registers.256registersarememorystoragelocations,oneregisterisusedtoselectoneofthestoragelocationsandiscalledthe"MemoryAddressRegister"or"MAR"forshort.Nowthatweknowwhat'sinit,wecanmakeasimplifieddiagramlikethis,andanevensimplerbusversion:
Thisisfullyhalfofacomputer.Acomputerhasjusttwoparts,andthisisoneofthem.Sonowyouknowhalfofwhatisinsideacomputer.EverypartismadeoutofNANDgates.Thatwasn’tverydifficultwasit?
Thereisoneproblemhere,andthatisthat256bytesisaverysmallsizeforacomputer’sRAM.Wemaybeabletogetawaywithitinthisbook,butifyouwantarealcomputer,it’sgoingtoneedaRAMwithmanymorebytestochoosefrom.
AlargerRAMcanbebuiltbyprovidingtworegistersthatareusedtoselectamemorystoragelocation.Thisallowstheuseof8X256decoders,andresultsinagridwith65,536intersections,andthusaRAMwith65,536differentlocationsinwhichtostoresomething.
Here’sanideaofwhatitwouldlooklike:(Don’tbothertryingtocountthegridlines,itwasonlypossibletofitabouthalfofthemontheprintedpage.)
Abuscarriesonebyteatatime,soselectingoneofthe65,536memorylocationsofthisRAMwouldbeatwo-stepprocess.First,onebytewouldhavetobeplacedonthe‘a’busandsetintoR0,thenthesecondbytewouldhavetobeplacedontothe‘a’busandsetintoR1.Nowyoucouldaccessthedesiredmemorylocationwiththebusandthe‘s’and‘e’bitsatthebottomofthedrawing.
Simplifyingagain,wehavesomethingthatlooksverymuchlikeour256byteRAM,itjusthasonemoreinputbit.
Fortherestofthisbook,wewillbeusingthe256byteRAMjusttokeepthingssimple.IfyouwanttoimagineacomputerwithalargerRAM,everytimewesendabytetotheMemoryAddressRegister,allyouhavetodoisimaginesendingtwobytesinstead.
NUMBERS
Wearegoingtoreturntothesubjectofcodesforamoment.PreviouslywelookedatacodecalledASCIIthatisusedtorepresentwrittenlanguage.Well,numbersareusedinwrittenlanguagetoo,sothereareASCIIcodesforthedigitszerothroughnine.Earlierwesaw20oftheASCIIcodesforpartofthealphabet,hereare10more,thecodesfornumbersinwrittenlanguage:
Thisisaveryusefulcode,butnoteverythingthatcomputersdohastodowithwrittenlanguage.Forothertasks,thereareothercodesthataresuitedbettertothosetasks.Whenitcomestonumbers,ifyouuseASCII,onebytecanbeanyofthe10digitsfrom0to9.Butsometimesthereisabytethatisalwaysusedtostoreanumber,andthatnumberwillneverbeprintedordisplayedonthescreen.Inthiscase,wecanuseadifferentcodethatdoesn'twasteanyofitspossiblestatesonlettersofthealphabetoranythingotherthannumbers.Sinceabytehas256possiblestates,youcanhavethiscoderepresent256differentnumbers.Sincewewanttoincludezero,thiscodestartsatzeroandgoesupto255.
Nowhowisthiscodearranged?TheASCIIaboveisnotusedatall;thisisa
completelydifferentcode.Thiscodedidnotrequireanycommitteemeetingstoinventbecauseitisthesimplestandmostobviouscodethatcomputersuse.Itistheclosestthingthereistoa‘natural’computercode.
Sincethisisalongchapter,hereisapreviewofthiscode.Itconsistsofassigninganumericvaluetoeachbitinthebyte.Tousethiscode,justturnonthebitsthatadduptothenumberyouwanttorepresent.
Toseehowthiscodeworks,whyitisusedincomputers,andhowthosebitvalueswerechosen,wewillexaminethesubjectofnumbersoutsideofcomputers.
Therearethreenumbersystemsthatyouareprobablyfamiliarwiththatwecananalyze.AsIseeit,thesethreesystemsareeachmadeupoftwoideasorelements–first,alistofsymbols,andsecond,amethodforusingthosesymbols.
ProbablytheoldestnumbersystemaroundisasimplethingcalledTallyMarks.Ithastwosymbols,“|”and“.”Themethodforusingthesesymbolsisthatyouwritedowna“|”foreachofthefirstfourthingsyouarecounting,thenforthefifthmark,youwritea“”acrossthefirstfour.Yourepeatthisoverandoveraslongasnecessaryandthenwhenyou’redoneyoucountthemarksbygroupsoffive–5,10,15,20,etc.Thissystemisverygoodforcountingthingsastheypassby,sayyourflockofsheep.Aseachanimalwalksby,youjustscratchdownonemoremark–youdon’thavetocrossout‘6’andwrite‘7’.Thissystemhasanotheradvantageinthatthereisactuallyonemarkforeachthingthathasbeencounted.Laterinthechapterwearegoingtodosomeinterestingthingswithnumbersthatmaygetconfusing,soinordertokeepthingsclear,wewillmakeuseofthisoldsystem.
DoyourememberRomannumerals?Itisanumbersystemthatalsoconsistsoftwoelements.Thefirstelementisthesymbols,justselectedlettersfromthealphabet,'I'forone,'Vforfive,'X'forten,'L'forfifty,'Cforonehundred,'D'forfivehundred,'M'foronethousand.Thesecondelementisamethodthatallowsyoutorepresentnumbersthatdon'thaveasinglesymbol.TheRomanmethodsaysthatyouwritedownmultiplesymbols,thelargestonesfirst,andaddthemup,exceptwhenasmallersymbolistoleftofalargerone,thenyousubtractit.So'II'istwo(addoneandone,)andTVisfour(subtractonefrom
five.)Oneofthethingsthatmadethisauthorveryhappyaboutthecomingoftheyear2000wasthefactthatRomannumeralsrepresentingtheyeargotalotsimpler.1999was'MCMXCIX,'youhavetodothreesubtractionsinyourheadjusttoreadthatone.2000wassimply'MM.'
Thenormalnumbersystemweusetodayalsoconsistsoftwoideas,butthesearetwoverydifferentideasthatcametousthroughArabiaratherthanRome.Thefirstoftheseideasisalsoaboutsymbols,inthiscase0,1,2,3,4,5,6,7,8and9.Thesedigitsaresymbolsthatrepresentaquantity.Thesecondideaisamethodthatwearesousedto,thatweuseitinstinctively.Thismethodsaysthatifyouwritedownonedigit,itmeanswhatitsays.Ifyouwritedowntwodigitsnexttoeachother,theoneontherightmeanswhatitsays,buttheonetoitsleftmeanstentimeswhatitsays.Ifyouwritedownthreedigitsrightnexttoeachother,theoneontherightmeanswhatitsays,themiddleonemeanstentimeswhatitsaysandtheoneontheleftmeansonehundredtimeswhatitsays.Whenyouwanttoexpressanumbergreaterthan9,youdoitbyusingmultipledigits,andyouusethismethodthatsaysthatthenumberofpositionstotheleftofthefirstdigittellsyouhowmanytimesyoumultiplyitbytenbeforeyouaddthemup.So,ifyouhave'246'apples,thatmeansthatyouhavetwohundredapplesplusfortyapplesplussixapples.
Sohowdoesthiswork?Anumberofanyamountcanbewrittenwiththedigitszerothroughnine,butwhenyougohigherthannine,youhavetousetwodigits.Whenyougoaboveninetynine,youhavetousethreedigits.Aboveninehundredninetynine,yougotofourdigits,etc.Ifyouarecountingupwards,thenumbersinanyoneofthepositionsgo'roundand'round-zerotonine,thenzerotonineagain,onandon,andwheneveryougofromninebacktozero,youincreasethedigittotheleftby1.Soyouonlyhavetensymbols,butyoucanusemorethanoneofthemasneededandtheirpositionswithregardtoeachotherspecifytheirfullvalue.
Thereissomethingoddaboutthisinthatthesystemisbasedonten,butthereisnosinglesymbolforten.Ontheotherhand,thereissomethingrightaboutthis-thesymbols'0'through'9'domakeuptendifferentsymbols.Ifwealsohadasinglesymbolforten,therewouldactuallybeelevendifferentsymbols.Sowhoeverthoughtofthiswasprettysmart.
OneofthenewideasinthisArabicsystemwastohaveasymbolforzero.Thisisusefulifyouwanttosaythatyouhavezeroapples,butitisalsoanecessarythingtokeepthepositionsofthedigitsstraight.Ifyouhave50applesor107apples,youneedthezerosinthenumberstoknowwhatpositioneachdigitis
actuallyin,soyoucanmultiplybytenthecorrectnumberoftimes.
NowthesetwoideasintheArabicnumbersystem(thedigitsandthemethod)haveonethingincommon.Theybothhavethenumbertenassociatedwiththem.Therearetendifferentdigits,andasyouadddigitstotheleftsideofanumber,eachpositionisworthtentimesmorethanthepreviousone.
Inschool,whentheyfirstteachchildrenaboutnumbers,theysaysomethingaboutournumbersystembeingbasedonthenumberten,becausewehavetenfingers.Sohere'sanoddquestion:Whatifthisnumbersystemhadbeeninventedbythree-toedsloths?Theyonlyhavethreefingersoneachhand,andnothumbs.Theywouldhaveinventedanumbersystemwithonlysixdigits-0,1,2,3,4and5.Couldthiswork?Ifyouhadeightapples,howwouldyouwriteit?Thereisnonumber'8'inthissystem.Theansweris,thatsincethefirstidea,thedigits,waschangedtoonlyhavesixdigits,thenthesecondidea,themethod,wouldalsohavetobechangedsothatasyouaddpositionstotheleft,eachonewouldhavetobemultipliedbysixesinsteadoftens.Thenthissystemwouldwork.Asyoucountyourapples,youwouldsay"0,1,2,3,4,5..."andthenwhat?
There'sno'6'forthenextnumber.Well,accordingtothemethod,whenyouwanttogobeyondthehighestdigit,yougobackto'o'andadda'1'totheleft.OK,"o,1,2,3,4,5,10,11,12."Nowyouhavecountedallofyourapples.Whatwouldthis'12'mean?Itwouldbethismany: Iguessyou'dcalliteight,butyou'dwriteit'12'.Veryodd,butitdoesworkout-1timessixplustwoequalseightapples,itfollowstheArabicmethod,butitisbasedonsixinsteadoften.Ifyoucontinuedcountingup,whenyougotto'15,'whichis (onetimessixplusfive,)thenextnumberwouldbe'20,'butthe'2'wouldmeantwosixes,orthismany: And55wouldbefollowedby100.The'1'inthatthirdpositionwouldbehowmany'36'stherewere(sixtimessix)
Thisisaveryoddnumbersystem,butguesswhat,youalreadyuseitinyoureverydaylife.Yes,thinkofthewaywewritetime,orthekindofclockthatshowsthenumbersonitsface.Therightdigitoftheminutesandsecondsfollowsournormalnumbers,0-9,0-9,overandover.Buttheleftdigitoftheminutesandsecondsonlygoes0-5.After59minutes,theclockgoestothenexthourand00minutes.Thereare60minutesinanhour,numberedfrom00to59.Thatleftpositionnevergetsover5.Thatpositionusesthenumbersystembasedonsixsymbols(0-5).Thehourpartoftheclocktellshowmany'60'sthereare,thoughyouwillneverseea60onthefaceoftheclock.Andyouaresousedtothisthatyoudon'thavetothinkaboutit.Whentheclocksays1:30,youknow
thatthisishalfwaybetween1:00and2:00,youdon'thavetodoanymathinyourheadtofigureitout.Haveyoueverhadtoaddtime?Ifyouadd40minutesand40minutes,youget80minutes,buttowritethatdowninhoursandminutes,youhavetofigureouthowmany60stherearein80,inthiscase1,thenfigureouthowmanyminutestherearebeyond60,inthiscase20.Soyouwrite1:20.The1represents60minutes,add20andyouhaveyour80again.Sothisisprettycomplicated,twodifferentnumbersystemsinthesamenumber!Butyouhavealreadybeenusingityourwholelife.
Thehourpositionsareevenstranger.Ona12hourclock,itskipszeroandgoes1-12AM,then1-12PM.Ona24hourclock,itgoesfrom00-23.Wewon’ttrytoanalyzethese.Thepointwewantedtomakewasthatyouarealreadyfamiliarwithnumbersystemsbasedonnumbersotherthanten.
Youcouldinventanumbersystemforanyamountofdigits,10or6likewe’veseenabove,or3or14oranynumberyouchoose.Butthesimplestonewouldbeifyouonlyhad2digits,0and1.Howwouldthisonework?Well,you’dcount0,1...andthenyou’realreadyoutofdigits–sobackto0andadd1ontheleft,makingthenextnumber10then11,thenyou’reoutofdigitsagain,so100then101,110,111then1000.Thissystemisbasedontwo,sothereareonlytwodigits,andasyouaddpositionstotheleft,eachoneisworthtwotimesmorethanthepreviousone.Therightpositionmeanswhatitsays,thenextonetotheleftmeanstwotimeswhatitsays,thenextmeansfourtimeswhatitsays,thenextmeanseighttimes,etc.Whenyougetdowntoonlyhavingtwopossibledigits,youdon’thavetodomuchmultiplicationtofigureoutthetotalvalueofaposition.Inthepositionthatisworth‘eight,’forexample,therecanonlybeaone,meaningone‘eight,’orazero,meaning‘noeights.’
Whilewe’reatit,let’simagineaverystrangeanimalwitheightfingersoneachhand.Thatanimalwouldhaveinventednumbersbasedonsixteen.Intheirsystem,theywouldbeabletowritetenthroughfifteeneachwithasinglesymbol.Onlywhentheyarrivedatsixteenwouldtheygetbackaroundto0andneedtoputa1inthepositiontotheleft.Toseehowthiswouldwork,weneedsixnewsymbols,solet’sjustusethefirstsixlettersofthealphabet.‘A’willmeanten,‘B’willmeaneleven,‘C’willmeantwelve,‘D’willmeanthirteen,‘E’
willmeanfourteenand‘F’willmeanfifteen.Onlyafterusingallsixteensymbolsintherightpositionwillwerunoutofsymbols,andthenextnumberwillbesixteen,written‘10’inthissystem.Ifyou’refamiliarwiththepoundsandouncessystemofweights,it’ssortoflikethissystem.Thereare16ouncesinapound,soyouknowthat8ouncesishalfapound.Adding9ouncesand9ouncescomesoutto1pound2ounces.
Hereisachartthatshowsfivedifferentnumbersystems.Thefirstcolumnistheoldtallymarksystemtokeepitsensible.
Ournormal0-9numbersarecalledthedecimalsystem,because‘dec’meansteninsomeancientlanguage.The0-5systemwouldbecalledthesenarysystem,because‘sen’meanssixinsomeotherancientlanguage.Thisnewsystemwithjust0and1iscalledthebinarysystembecause‘bi’meanstwo,alsobecauseofsomeancientlanguage.Thisothernewsystem,the0-Fsystem,willbecalledthehexadecimalsystem,because‘hex’isanotherancientwordthatmeanssixand‘dec’stillmeansten,soit’sthesixplustensystem.
Anothermethodofnamingdifferentnumbersystemsistocallthembythenumbertheyarebasedon,suchas‘base10’or‘base2,’etc.meaningdecimalorbinary,etc.Butnoticethatthenumberaftertheword‘base’iswritteninthe
decimalsystem.‘2’writteninbinaryis‘10,’so‘base10’wouldmeanbinaryifthe‘10’waswritteninbinary.Infact,everynumbersystemwouldbe'base10'ifthe'10'waswritteninthatsystem'snumbers!Sowecouldtalkaboutbase2,base6,base10andbase16ifwewantedto,aslongaswerememberthatthosebasenumbersarewrittenindecimal.Ifwetalkaboutbinary,senary,decimalandhexadecimal,it'sthesamething,justpossiblyalittlelessconfusing.
Again,inournormaldecimalnumbers,therightmostpositionisthenumberofones.Thenextpositiontotheleftisthenumberoftens,etc.Eachpositionisworthtentimesthepreviousone.Inthebinarysystem,therightmostpositionisalsothenumberofones,butthenextpositiontotheleftisthenumberof'twos,'thenexttotheleftisthenumberof'fours,'thenextis'eights.'Eachpositionisworthtwotimestheamounttoitsright.Sinceeachpositionhasonlytwopossiblevalues,zeroorone,thisissomethingthatwecoulduseinabyte.
Thisisthepointofthischapter.Thebinarynumbersystemisa'natural'matchtothecapabilitiesofcomputerparts.Wecanuseitasacode,withoffrepresentingzeroandonrepresentingone,followingtheArabicnumbermethodwithonlytwosymbols.Inabyte,wehaveeightbits.Whenweusethiscode,thebitontherightwillbeworth1whenthebitison,orowhenitisoff.Thenextbittotheleftwillbeworth2whenitison,orowhenitisoff.Thenexttotheleftis4,andsoonwith8,16,32,64and128.Intheorderwenormallyseethem,thevaluesoftheeightbitslooklikethis:1286432168421.
Inthiscode,00000001meansone,00010000meanssixteen,00010001meansseventeen(sixteenplusone,)11111111means255,etc.Inaneight-bitbyte,wecanrepresentanumberanywherefromoto255.Thiscodeiscalledthe"binarynumbercode."
Thecomputerworksjustfinewiththisarrangement,butitisannoyingforpeopletouse.Justsayingwhatisinabyteisaproblem.Ifyouhave00000010,youcancallit"zerozerozerozerozerozeroonezerobinary"oryoucanmentallytranslateittodecimalandcallit"two,"andthatisusuallywhatisdone.Inthisbookwhenanumberisspelledout,suchas'twelve,'itmeans12inourdecimalsystem.Abinary00000100wouldbecalled'four,'becausethatiswhatitworksouttobeindecimal.
Actually,inthecomputerindustry,peopleoftenusehexadecimal,(andtheyjustcallit'hex'.)Ifyoulookatthechartabove,youcanseethatfourdigitsofbinarycanbeexpressedbyonedigitofhex.Ifyouhaveabytecontaining00111100,youcantranslateitto60decimal,orjustcallit"3Chex."Nowdon'tworry,
we'renotgoingtousehexinthisbook,butyoumayhaveseenthesetypesofnumberssomewhere,andnowyouknowwhatthatwasallabout.
Addresses
Nowthatwehavethebinarynumbercode,wecanuseitforvariouspurposesinourcomputer.Oneofthefirstplaceswewilluseit,isintheMemoryAddressRegister.Thepatternofbitsthatweputintothisregisterwillusethebinarynumbercode.ThebitsofthisnumberinMARthenselectoneofthe256RAMstoragelocations.ThenumberinMARisconsideredtobeanumbersomewherebetweenoand255,andthuseachofthe256RAMbytescanbeconsideredtohaveanaddress.
Thisisfairlysimple,butapointneedstobemadehereaboutexactlywhatismeantbyanaddressinsideofacomputer.Inaneighborhoodofhomes,eachhousehasanaddress,like125MapleStreet.Thereisasignatthecornerthatsays"MapleSt."andwrittenonthehousearethenumerals"125."Thisisthewaywenormallythinkofaddresses.Thepointtobemadehereisthatthehousesandstreetshavenumbersornameswrittenonthem.Inthecomputer,thebytedoesnothaveanyidentifyinginformationonitorcontainedinit.ItissimplythebytethatgetsselectedwhenyouputthatnumberintheMemoryAddressRegister.Thebytegetsselectedbyvirtueofwhereitis,notbyanyotherfactorthatiscontainedatthatlocation.Imagineaneighborhoodofhousesthathadsixteenstreets,andsixteenhousesoneachstreet.Imaginethatthestreetsdonothavesignsandthehousesdonothavenumberswrittenonthem.Youwouldstillbeabletofindanyspecifichouseifyouweretold,forexample,togoto'thefourthhouseontheseventhstreet.'Thathousestillhasanaddress,thatis,amethodoflocatingit,itjustdoesn'thaveanyidentifyinginformationatthelocation.SoacomputeraddressisjustanumberthatcausesacertainbytetobeselectedwhenthataddressisplacedintotheMemoryAddressRegister.
THEOTHERHALFOFTHECOMPUTER
TheotherhalfofthecomputerisalsomadeultimatelyofnothingbutNANDgates,anditprobablyhasfewertotalpartsthantheRAMwehavebuilt,butitisnotlaidoutsoregularlyandrepetitively,soitwilltakealittlelongertoexplain.Wewillcallthishalfofthecomputerthe“CentralProcessingUnit,”orCPUforshort,becauseitdoessomethingwithandtothebytesinRAM.It“processes”them,andwewillseewhatthatmeansinthenextfewchapters.Thethingthatiscommontobothsidesofthecomputeristhebus.
HerearethebeginningsoftheCPU.TheRAMisshownontheright,andthebusmakesabigloopbetweenthetwobusconnectionsontheRAM.TheCPUstartswithsixregistersconnectedtothebus.ThesesixregistersarealloftheplacesthattheCPUwilluseto“process”bytes.That’snotsocomplicated,isit?
Thebigboxlabeled“ControlSection”inthemiddleofthediagramwillbeexaminedindetaillater.Itcontrolsallofthe‘set’and‘enable’bitsintheCPUandtheRAM.Theboxeswiththequestionmarkswillbeexplainedimmediatelyfollowingthischapter.Fornow,wearegoingtolookatwherethebytescangowithintheCPU.
R0,R1,R2,andR3areregistersthatareusedasshort-termstorageforbytesthatareneededintheCPU.Theirinputsandoutputsareconnectedtothebus.Theycanbeusedformanydifferentpurposes,sotheyareknownas"generalpurposeregisters."
Theregistercalled'TMP'meanstemporary.Itsinputcomesfromthebus,andits
outputgoesdownwardtooneandthentheotherofthequestionmarkedboxes.TMPhasa'set'bit,butno'enable'bitbecauseweneverhaveareasontoturnitsoutputoff.
Thelastregisteriscalledtheaccumulator,orACCforshort.Thisisawordthatcomesfromthedaysoftheoldmechanicaladdingmachines(pre1970.)Iguessitmeantthatasyouaddedupacolumnofnumbers,itwould'accumulate'arunningtotal.Inacomputer,itjustmeansthatittemporarilystoresabytethatcomesfromthatbigquestionmarkedbox.TheoutputofACCisthenconnectedtoouroldfriend,thebus,soitcanbesentsomewhereelseasneeded.
TheregistersintheCPUandRAMaretheplaceswherethecontentsofbytescomefromandgotoasthecomputeroperates.Allmovementsinvolveenablingoneregisterontothebus,andsettingthecontentsofthebusintoanotherregister.
Nowwewilllookatwhatisinthoseboxeswiththequestionmarks.
MOREGATES
WehaveusedNAND,ANDandNOTgatessofar.Therearetwomorecombinationgatesthatweneedtodefine.Thefirstisbuiltlikethis:
AllitdoesistoNOTthetwoinputstooneofourgoodoldNANDgates.Hereisthechartforit,showingtheintermediatewiressoitiseasytofollow.
Inthiscase,whenbothinputsareoff,theoutputisoff,butifeither'a'OR'b'ison,orboth,thentheoutputwillbeon.Soithasanotherverysimplename,itiscalledthe"ORgate."Insteadofdrawingalltheparts,ithasitsowndiagramshapedsomethinglikeashield.Thediagramandchartlooklikethis:
LiketheANDgate,youcanbuildORgateswithmorethantwoinputs.JustaddanotherORgateinplaceofoneoftheinputs,andyouwillthenhavethreeinputs,anyoneofwhichwillturntheoutputon.AlsoliketheANDgate,everytimeyouaddaninput,thenumberoflinesonthechartwilldouble.WiththeORgate,onlythelinethathasallinputsoffwillhavetheoutputoff.Alltherestofthelineswillshowtheoutputbeingon.
Thelastcombinationgateweneedheretakesfivegatestomake,butwhatitultimatelydoesisquitesimple.SimilartotheORgate,theoutputisonwheneitherinputison,butinthisversion,theoutputgoesbackoffifbothinputsareon.SoitiscalledanExclusiveORgate,orXORgateforshort.TheoutputisonifeitherORtheotherinputison,exclusively.OnlyifitisOR,notifitisAND.Anotherwaytolookitatitistheoutputcomesonifoneandonlyoneinputison.Stillanotherwaytolookatitistheoutputisoffiftheinputsarethesame,andoniftheinputsaredifferent.
ThesimplifieddiagramlookssimilartoanORgate,butithasadoublecurvedlineontheinputside.Thediagramandchartlooklikethis:
Wenowhavefourkindsofgatesthattaketwoinputsandmakeoneoutput.TheyareNAND,AND,ORandXOR.Hereisachartthatmakesitprettysimple:
Forthefourpossibleinputcombinationsof‘a’and‘b,’eachtypeofgatehasitsownsetofoutputstates,andthenamesofthegatescanhelpyourememberwhichiswhich.
InspiteofthefactthateverythinginthecomputerismadeoutofNANDgates,wearenotgoingtobeusinganyNANDgatesbythemselvesinthiscomputer!NowthatwehaveusedthemtobuildAND,OR,XORandNOTgates,andthememorybit,wearedonewiththeNANDgate.ThankyouMr.NANDgate,byebyefornow.
MessingwithBytes
Individualgatesoperateonbits.Twobitsin,onebitout.ButtheRAMstoresandretrievesabyteatatime.Andthebusmovesabyteatatime.HereintheCPU,wewanttobeabletoworkonawholebyteatonetime.Wewantsome'gates'thataffectanentirebyte.Inthechapteronthebus,wesawhowthecontentsofabytecanbecopiedfromoneregistertoanother.Thisisusuallyreferredtoasmovingabyte.Nowwearegoingtoseesomevariationsonthis.
Firstwewillseethreewaysthatwecanchangethecontentsofabyteasitmovesfromoneregistertoanother.Second,wewillseefourwaysthatwecantakethecontentsoftwobytes,andhavetheminteractwitheachothertocreatethecontentsforathirdbyte.Theseareallofthethingsthatcomputersactuallydotobytes.Allthingsultimatelycomedowntothesesevenoperations.
THELEFTANDRIGHTSHIFTERS
Theshifterisveryeasytobuild.Itdoesn’tuseanygatesatall,itjustwiresupthebusabitoddly.Itisdonelikethis:
Thisshowstworegistersconnectedbyarightshifter.Theshifterisjustthewiresbetweenthetworegisters.Whenthe‘e’bitofR1isturnedon,andthe‘s’bitofR2isturnedonandthenoff,allofthebitsinR1arecopiedintoR2,buttheyareshiftedoveroneposition.Theoneatthebottom(shiftout)canbeconnectedtosomeotherbitinthecomputer,butisoftenconnectedbacktotheoneonthetop(shiftin)andwhenthatisdone,therightmostbitwrapsaroundtotheleftmostbitattheotherendofthebyte.
Arightshifterwillchange01000010,to00100001.
If‘shiftout’isconnectedto‘shiftin,’arightshiftwillchange00011001to10001100
Aleftshifterwillchange01000010to10000100.Theleftshifteriswireduplikeso:
Onceagain,wehavebusversionsofthesedrawings.Theyeachhavean‘i’and‘o’bus,andalsooneinputandoutputbit,likethis:
Nowofwhatuseisthis?Themindsofprogrammershavecomeupwithallsortsofthings,buthereisaninterestingone.Assumethatyouareusingthebinarynumbercode.Youhavethenumber00000110inR1.Thatcomesouttothedecimalnumber6.NowshiftthatcodeleftintoR2.R2willthenbe00001100.Thiscomesouttothedecimalnumber12.Whatdoyouknow,wehavejustmultipliedthenumberby2.Thisisthebasisofhowmultiplicationisdoneinourcomputer.Howyoumultiplybysomethingotherthan2willbeseenlater,butthisishowsimpleitis,justshiftthebits.Thisissimilartosomethingwedowithdecimalnumbers.Ifyouwanttomultiplysomethingbyten,youjustaddazerototherightside,effectivelyshiftingeachdigitleftoneposition.Inthebinarysystem,thisonlyresultsinmultiplyingbytwobecausetwoiswhatthesystemisbasedon.
Sothat’stheshifter,nogatesatall.
THENOTTER
ThisdeviceconnectstworegisterswitheightNOTgates.Eachbitwillbechangedtoitsopposite.Ifyoustartwith01101000,youwillendupwith10010111.Thisoperationisusedformanypurposes,thefirstbeinginsomearithmeticfunctions.Wewillseeexactlyhowthisworkssoonafterwedescribeafewotherthings.AnothernameforaNOTgateisan"inverter,"becauseitmakestheoppositeofwhatyougiveit,turnsitupsidedown,orinvertsit.
Sincetheinputandtheoutputarebotheightwires,we'llsimplifybyusingourbustypepicture.
THEANDER
TheANDertakestwoinputbytes,andANDseachbitofthosetwointoathirdbyte.Asyoucansee,theeightbitsofthe'a'inputbusareconnectedtotheuppersideofeightANDgates.Theeightbitsofthe'b'inputbusareconnectedtothelowersideofthesameeightANDgates.TheoutputsoftheeightANDgatesformthebusoutput'c'ofthisassembly.Withthis,wecanANDtwobytestogethertoformathirdbyte.
Therearemanyusesforthis.Forexample,youcanmakesurethatanASCIIlettercodeisuppercase.Ifyouhavethecodefortheletter'e'inR0,01100101,youcouldputthebitpattern11011111intoR1andthenANDR1andR0andputtheanswerbackintoR0.AllofthebitsthatwereoninR0willbecopiedbacktoR0exceptforthethirdbit.Whetherthethirdbithadbeenonoroffbefore,itwillnowbeoff.R0willnowcontain01000101,theASCIIcodefor'E.'ThisworksforallASCIIlettercodesbecauseofthewayASCIIisdesigned.
HereisasimplerbustypepicturefortheANDer.
THEORER
TheORertakestwoinputbytes,andORseachbitofthosetwointoathirdbyte.Asyoucansee,theeightbitsofthe'a'inputbusareconnectedtotheuppersideofeightORgates.Theeightbitsofthe'b'inputbusareconnectedtothelowersideofthesameeightORgates.TheoutputsoftheeightORgatesarethebusoutput'c'ofthisassembly.Withthis,wecanORtwobytestogethertoformathirdbyte.
Whatistheuseofthis?Therearemany,buthereisoneofthem.SayyouhavetheASCIIcodefortheletter'E'inR0,01000101.Ifyouwanttomakethisletterbelowercase,youcouldputthebitpattern00100000intoR1andthenORR0andR1andputtheanswerbackintoR0.Whatwillhappen?AllofthebitsofR0willbecopiedbackintoR0astheywereexceptthethirdbitwillnowbeonnomatterwhatithadbeen.R0willnowbe01100101,theASCIIcodefor'e.'ThiswillworknomatterwhatASCIIlettercodewasinR0becauseofthewayASCIIwasdesigned.
HereisasimplerbustypepicturefortheORer.
THEEXCLUSIVEORER
TheXORertakestwoinputbytes,andXORseachbitofthosetwointoathirdbyte.Asyoucansee,theeightbitsofthe'a'inputbusareconnectedtotheuppersideofeightXORgates.Theeightbitsofthe'b'inputbusareconnectedtothelowersideofthesameeightXORgates.TheoutputsoftheeightXORgatesarethebusoutput'c'ofthisassembly.Withthis,wecanXORtwobytestogethertoformathirdbyte.
Whatistheuseofthis?Again,imaginativepeoplehavecomeupwithmanyofuses.Buthereisoneofthem.SayyouhaveonecodeinR1andanothercodeinR2.Youwanttofindoutifthosetwocodesarethesame.SoyouXORR1andR2intoR1.IfR1andR2containedthesamepatterns,thenR1willnowbeallzeros.Itdoesn'tmatterwhatpatternof0sand1swasinR1,ifR2containedthesamepattern,afteranXOR,R1willbeallzeros.
Sincebothoftheinputsandtheoutputarealleightwires,we'llsimplifybyusingourbustypepicture.
THEADDER
Thisisacombinationofgatesthatissurprisinglysimpleconsideringwhatitdoes.Inourbinarynumbersystem,wehavenumbersintherangeof0to255representedinabyte.Ifyouthinkabouthowadditionisdonewithtwoofourregulardecimalnumbers,youstartbyaddingthetwonumbersintherightcolumn.Sincethetwonumberscouldeachbeanywherefrom0to9,thesumofthesetwowillbesomewherefrom0to18.Iftheanswerisanywherefrom0to9,youwriteitdownbelowthetwonumbers.Iftheanswerisfrom10to18,youwritedowntherightdigit,andcarrythe1toaddtothenextcolumntotheleft.
Inthebinarynumbersystem,itisactuallymuchsimpler.Ifyoudothesametypeofadditioninbinary,thetwonumbersintherightcolumncaneachonlybe0or1.Thustheonlypossibleanswersforaddingtherightcolumnoftwobinarynumberswillbe0,1or10(zero,oneortwo).Ifyouadd0+0,youget0,1+0or0+1youget1,1+1yougetointherightcolumn,andcarry1tothecolumntotheleft.
Thegateswehavedescribedcaneasilydothis.AnXORofthetwobitswilltelluswhattherightcolumnanswershouldbe,andanANDofthetwobitswilltelluswhetherweneedtocarrya1tothecolumnontheleft.Ifonebitison,andtheotheroneisoff,thatis,weareaddinga1anda0,theanswerfortherightcolumnwillbe1.Ifbothnumbersare1,orbothnumbersareo,therightcolumnwillbeo.TheANDgateturnsononlyinthecasewherebothinputnumbersare1.
Sowehaveaddedtherightcolumneasily.Nowwewanttoaddthenextcolumntotheleft.Shouldbethesame,right?Therearetwobitsthatcouldbe0or1,butthistimewealsohavethepossibilityofacarryfromthepreviouscolumn.Soit’snotthesame,thistimewearereallyaddingthreenumbers,thetwobitsinthiscolumn,plusthepossiblecarryfromthepreviouscolumn.
Whenaddingthreebits,thepossibleanswersare0,1,10or11(zero,one,twoorthree.)Itismorecomplex,butnotimpossible.Hereisthecombinationthatdoesit:
TheleftXORtellsusif‘a’and‘b’aredifferent.Iftheyare,and‘carryin’isoff,orif‘a’and‘b’arethesameand‘carryin’ison,thentherightXORwillgenerate1asthesumforthecurrentcolumn.ThelowerANDgatewillturnon‘carryout’ifbothinputsareon.TheupperANDgatewillturnon‘carryout’if‘carryin’andoneoftheinputsareon.Thisisthesimplicityofhowcomputersdoaddition!Nowthatweseethatitworks,wecanmakeasimplerpictureofit:
Tomakeanadderthataddstwobytestogether,weneedaonebitadderforeachbitofthebytes,withthecarryoutputofeachbitconnectedtothecarryinputofthenext.Noticethateverybithasacarryin,eventhefirstbit(therightcolumn.)Thisisusedwhenwewanttoaddnumbersthatcanbelargerthan255.
Andthesimplifiedpictureofitwithbusinputsandoutput:
Thecarryoutputbitoftheleftmost(top)columnwillturnonifthesumofthetwonumbersisgreaterthan255,andthisbitwillbeusedelsewhereinthecomputer.
Thisishowcomputersdoaddition,justfivegatesperbit,andthecomputercan
doarithmetic!
THECOMPARATORANDZERO
Allofthethingswehavedescribedabovetakeoneortwobytesasinput,andgenerateonebyteofoutput.Theshiftersandtheadderalsogenerateoneextrabitofoutputthatisrelatedtotheiroutputbyte.Thecomparatoronlygeneratestwobitsofoutput,notawholebyte.
ThecomparatorisactuallybuiltrightintotheXORerbecauseitcanmakeuseofthegatesthatarealreadythere.TheXORergeneratesitsbyteofoutput,andthecomparatorgeneratesitstwobits.Thesetwofunctionsarenotreallyrelatedtoeachother,itjusthappenstobeeasytobuilditthisway.
Whatwewantthecomparatortodo,istofindoutwhetherthetwobytesontheinputbusareexactlyequal,andifnot,whethertheoneonthe'a'busislargeraccordingtothebinarynumbersystem.
Theequalthingisprettysimple.XORgatesturnoffwhentheinputsarethesame,soifalloftheXORgatesareoff,thentheinputsareequal.
Todeterminethelargeroftwobinarynumbersisalittletrickier.Youhavetostartwiththetwotopbits,andifoneisonandtheotherisoff,thentheonethatisonisthelargernumber.Iftheyarethesame,thenyouhavetocheckthenextlowerpairofbitsetc.,untilyoufindapairwheretheyaredifferent.Butonceyoudofindapairthataredifferent,youdon'twanttocheckanymorebits.Forexample,00100000(32)islargerthan00011111(31.)Thefirsttwobitsarethesameinbothbytes.Thethirdbitisoninthefirstbyteandoffinthesecond,andthereforethefirstbyteislarger.Althoughtherestofthebitsareoninthesecondbyte,theirtotalislessthantheonebitthatisoninthefirstbyte.
Thatiswhatwewanttohavehappen,andittakesfivegatestimeseightpositionstoaccomplishit.SincewearestartingwiththeXORer,wewilladdfourmoregatestoeachpositionasshowninthisdiagram.Rememberintheadder,wehadacarrybitthatpassedfromthelowestbitpositionupthroughtothehighestbit.Inthecomparator,wehavetwobitsthatpassdownfromthehighestbitpositiontothelowest.
Hereisonebitofthecomparator.YoucanseetheoriginalXORgate,labeled'1',connecteduptoonebitofeachinputbusontheleft,andgeneratingonebitfortheoutputbusontheright.
Iftheoutputofgate1ison,thatmeansthat'a'and'b'aredifferent,orunequal.Weaddgate2,whichwillturnonwhen'a'and'b'areequal.
Ifgate2isonateveryposition,thengate3willbeonateverypositionaswell,andthebitthatcomesoutofthebottomtellsusthatthetwoinputbytesareequal.
Gate4turnsonifthreethingsaretrue.1)Bits'a'and'b'aredifferent.2)Bit'a'istheonethatison.3)Allbitsabovethispointhavebeenequal.Whengate4turnson,itturnsgate5on,andthatturnsoneveryothergate5belowthispoint,andthereforethe'alarger'outputofthecomparator.
Whenbyte'b'isthelargerone,boththe'equal'bitandthe'alarger'bitwillbeoff.
Youstackupeightofthesebitcomparatorslikethefollowingdiagram,witha'1'and'0'connectedtothetoponetogetitstarted.YoustillhavetheXORfunctioncomingoutat'c,'andnowthetwocomparatorbitsatthebottom.
Simplifyingagain,wewillgobacktothebus-typeXORdiagram,andjustaddthetwonewoutputbitsofthecomparator.
Thereisonemorethingthatwearegoingtoneedinourcomputerthatgivesusanotherbitofinformation.Thisisasimplegatecombinationthattakesawholebyteasinput,andgeneratesonlyonebitasoutput.Theoutputbitturnsonwhenallofthebitsinthebyteareoff.Inotherwords,theoutputbittellsuswhenthecontentsofthebyteisallzeros.
ItissimplyaneightinputORgateandaNOTgate.WhenanyoftheinputstotheORgateareon,itsoutputwillbeon,andtheoutputoftheNOTgatewillbeoff.OnlywhenalleightinputsoftheORareoff,anditsoutputisthereforeoff,willtheoutputoftheNOTgatebeon.Thesimplerbusrepresentationisshownontheright.
LOGIC
Thesubjectofthinkinghasbeentheobjectofmuchstudyandspeculationthroughtheages.TherewasamaninancientGreecenamedAristotlewhodidalotofworkinthisarea.Hemusthavemetalotofillogicalpeopleinhislife,becauseheinventedasubjectthatwassupposedtohelppeoplethinkmoresensibly.
Oneofhisideaswasthatifyouhavetwofacts,youmaybeabletoderiveathirdfactfromthefirsttwo.Inschooltheysometimesgiveteststhatpresenttwofacts,thentheygiveyouathirdfactandaskwhetherthethirdfactis'logical'basedonthefirsttwo.Youmayrememberquestionssuchas:
IfJoeisolderthanBill,AndFredisolderthanJoe,ThenFredisolderthanBill.TrueorFalse?
Or
Childrenlikecandy.Janeisachild.ThereforeJanelikescandy.TrueorFalse?
Aristotlecalledhisstudyofthissortofthing'Logic'
Theonlyrelevancethishastoourdiscussionofcomputersisthisword'logic'Aristotle'slogicinvolvedtwofactsmakingathirdfact.Manyofourcomputerparts,suchasANDgates,taketwobitsandmakeathirdbit,oreightANDgatestaketwobytesandmakeathirdbyte.Andso,thethingsthatthesegatesdo,hascometobeknownaslogic.TheremaybeANDlogicandORlogicandXORlogic,butthegeneraltermforallofthemislogic.
ANDing,ORingandXORingtaketwobytestomakeathird,sotheyfitthisdefinitionoflogicprettywell.ShiftingandNOTinghavealsocometobeknownaslogiceventhoughtheyonlytakeonebyteofinputtogeneratetheiroutput.TheADDer,althoughitishastwoinputsandisalsoverylogical,somehowisnotknowntobeinthecategoryoflogic,itisinitsowncategory,arithmetic.
Soallofthewaysthatwehavedescribedaboveofdoingthingstobytescomeundertheheadingof'arithmeticandlogic'
THEARITHMETICANDLOGICUNIT
Nowwehavebuiltsevendifferentdevicesthatcandoarithmeticorlogiconbytesofdata.Wearegoingtakeallsevenofthesedevices,putthemtogetherinoneunit,andprovideamethodofselectingwhichoneofthesedeviceswewanttouseatanygiventime.Thisiscalledthe"ArithmeticandLogicUnit,'or"ALU"forshort.
Allsevendevicesareconnectedtoinput'a,'thedevicesthathavetwoinputsarealsoconnectedtoinput'b.'Allsevendevicesareconnectedtotheinputsatalltimes,buteachoutputisattachedtooneofthoseenablers.Thewiresthatturn
theenablerson,areconnectedtotheoutputsofadecoder,thusonlyoneenablercanbeonatagiventime.Sevenofthedecoder'soutputsenableasingledevicetocontinueontothecommonoutput,'c.'Theeighthoutputofthedecoderisusedwhenyoudon'twanttoselectanydeviceatall.Thethreeinputwirestothedecoderarelabeled'op,'becausetheychoosethedesired'operation.'Theonelittlecomplicationhereisthecarrybitsfromtheadder,andthe‘shiftin’and‘shiftout’bitsfromtheshifters.Theseareusedinverysimilarways,andsofromhereonoutwewillrefertoallofthemascarrybits.Theadderandbothshifterstakecarryasaninput,andgeneratecarryasanoutput.SothethreecarryinputsareconnectedtoasingleALUinput,andoneofthethreeoutputsisselectedalongwiththebusoutputofitsdevice.Lookattherightmostoutputofthe3X8decoderabove,andseethatitenablesboththeadderbusandtheaddercarrybit.
Whatdowehavehere?Itisaboxthathastwobusinputs,onebusoutputandfourotherbitsinandfourotherbitsout.Threeoftheinputbitsselectwhich“operation”willtakeplacebetweentheinputandoutputbuses.Again,nowthatweknowwhat’sinitandhowitworks,wedon’tneedtoshowallofitsparts.Hereisasimplifiedwaytodrawit:
Noticethatthethreesinglebitinputslabeled“op,”above,canhaveeightdifferentcombinations.Sevenofthosecombinationsselectoneofthedevicesdescribedpreviously.Theeighthcombinationdoesnotselectanyoutputbyte,butthe‘alarger’and‘equal’bitsstillwork,astheydoatalltimes,sothisisthecodetochooseifyouonlywanttodoacomparison.
Thecombinationofbitsat‘op’meansomething.Thatsoundslikeanothercode.Yes,hereisathree-bitcodethatwewillmakeuseofsoon.
TheArithmeticandLogicUnitistheverycenter,theheartofthecomputer.Thisiswherealloftheactionhappens.I'llbetthisisalotlesscomplicatedthanyouthought.
MOREOFTHEPROCESSOR
Thereisonemorelittledeviceweneed.Itisaverysimplething,ithasabusinput,abusoutputandoneotherinputbit.Itisverysimilartoanenabler.SevenofthebitsgothroughANDgates,andoneofthemgoesthroughanORgate.Thesinglebitinputdetermineswhathappenswhenabytetriestopassthroughthisdevice.Whenthe'bus1'bitisoff,allofthebitsoftheinputbuspassthroughtotheoutputbusunchanged.Whenthe'bus1'bitison,theinputbyteisignoredandtheoutputbytewillbe00000001,whichisthenumberlinbinary.Wewillcallthisdevicea'bus1'becauseitwillplacethenumber1onabuswhenweneedit.
Nowwecanputthis'bus1'andtheALUintotheCPU.WewillchangewherethewiresgoinandoutoftheALUsoitfitsourdiagrambetter.Thebusinputscomeinthetop,thebusoutputcomesoutthebottomandalloftheinputandoutputbitsareontheright.
TheoutputoftheALUisconnectedtoACC.ACCreceives,andtemporarilystores,theresultofthemostrecentALUoperation.TheoutputofACCisthenconnectedtothebus,soitscontentscanbesentsomewhereelseasneeded.
WhenwewanttodoaoneinputALUoperation,wehavetosetthethree‘op’bitsoftheALUtothedesiredoperation,enabletheregisterwewantontothebus,andsettheanswerintoACC.
ForatwoinputALUoperation,therearetwosteps.FirstweenableoneoftheregistersontothebusandsetitintoTMP.Thenweenablethesecondregisterontothebus,choosetheALUoperation,andsettheanswerintoACC.
Asyoucansee,wecannowmovebytesofdatatoandfromRAM,toandfromtheRegisters,throughtheALUtoACC,andfromthere,intoaregisterorRAMifweturntheappropriateenableandsetbitsonandoffattherighttime.Thisiswhathappensinsideofcomputers.That’snotsocomplicated,isit?
Thereisonlyonethingmissinghere,andthathastodowithallofthesecontrolbitsontheregisters,ALUandRAM.TheRAMhasthreecontrolbits,onetosetMAR,onetosetthecurrentlyselectedbytein,onetoenablethecurrentlyselectedbyteout.Eachoftheregisters,R0,R1,R2,R3andACChaveasetandanenablebit,TMPonlyhasasetbit,bus1hasacontrolbit,andtheALUhasthosethree‘op’bitsthatselectthedesiredoperation.
Weneedsomethingthatwillturnallofthesecontrolbitsonandoffattheappropriatetimessowecandosomethingthatisuseful.Nowitistimetolookintothatboxlabeled'ControlSection.'
THECLOCK
Weneedtoturntheappropriatecontrolbitsonandoffattheappropriatetimes.Wewilllookattheappropriatebitslater,firstwewilllookattheappropriatetimes.
Hereisanewkindofdrawing,wewillcallitagraph.Itshowshowonebitchangesovertime.Timestartsontheleftandmarchesforwardtotheright.Thelineonthegraphhastwopossiblepositions,upmeansthebitison,anddownmeansthebitisoff.
Thisgraphshowsbit'X'goingonandoff,onandoffregularly.Therecouldbeatimescaleonthebottomtoshowhowfastthisishappening.Ifthewholewidthofthepagerepresentedonesecond,thenbit'X'wouldbegoingonandoffabouteighttimespersecond.Butwewon'tneedatimescaleinthesegraphs,aswewillonlybeconcernedwiththerelativetimingbetweentwoormorebits.Thespeedinanactualcomputerwillbeveryfast,suchasthebitgoingonandoffabilliontimespersecond.
Whensomethingrepeatssomeactionregularly,oneofthoseactions,individually,iscalledacycle.Thegraphaboveshowsabouteightcycles.Youcansaythatfromonetimethebitturnsontothenexttimethebitturnsonisacycle,oryoucansaythatfromthemiddleoftheofftimetothemiddleofthenextofftimeisthecycle,aslongasthecyclestartsatonepointintimewhenthebitisatsomestageofitsactivity,andcontinuesuntilthebitgetsbacktothesamestageoftheactivityagain.Theword'Cycle'comesfromtheword'circle,'sowhenthebitcomesfullcircle,thatisonecycle.
TherewasascientistwholivedinGermanyinthe1800'swhodidsomeoftheearlyresearchthatleduptoradio.HisnamewasHeinrichHertz,andamongotherthings,hestudiedelectricitythatwasgoingonandoffveryquickly.Somedecadesafterhisdeath,itwasdecidedtousehisnametodescribehowfastelectricitywasgoingonandoff,orhowmanycyclesoccurredpersecond.Thus,oneHertz(orHzforshort)meansthattheelectricityisgoingonandoffoncepersecond.500Hzmeans500timespersecond.Forfasterspeedswerunintothoseancientlanguagesagain,andonethousandtimespersecondiscalledakilohertz
orkHzforshort.Goingonandoffamilliontimespersecondiscalledamegahertz,ormHzforshort,andabilliontimesiscalledagigahertz,orgHzforshort.
Everycomputerhasonespecialbit.Allotherbitsinacomputercomefromsomewhere,theyaresetonandoffbyotherbitsorswitches.Thisonespecialbitturnsonandoffallbyitself.Butthereisnothingmysteriousaboutit,itjustgoesonandoffveryregularlyandveryquickly.Thisspecialbitisbuiltverysimply,likethis:
Thisseemsasillythingtodo.JustconnectaNOTgate’soutputbacktoitsinput?Whatwillthisdo?Well,ifyoustartwiththeoutputon,theelectricitytravelsbacktotheinput,whereitentersthegatewhichturnstheoutputoff,whichtravelsbacktotheinputwhichturnstheoutputon.Yes,thisgatewilljustgoonandoffasquicklyaspossible.Thiswillactuallybetoofasttobeusedforanything,andsoitcanbesloweddownjustbylengtheningthewirethatmakestheloop.
Thesimplifieddiagramshowsthistobetheonespecialbitinthecomputerthathasanoutputbutdoesnothaveanyinputs.
Thisbithasaname.Itiscalledtheclock.Nowweusuallythinkofaclockasathingwithadialandhands,orsomenumbersonascreen,andwehaveseensuchclocksinthecornerofacomputerscreen.Unfortunately,someonenamedthistypeofbit,aclock,andthenamestuckwiththecomputerpioneers.Itcouldhavebeencalledthedrumbeatorthepacesetterortheheartortherhythmsection,buttheycalleditaclock.Thatiswhatwewillmeanwhenwesayclockthroughouttherestofthisbook.Iguessit’saclockthatticks,butdoesn’thaveadial.Ifwewanttotalkaboutthetypeofclockthattellsyouwhattimeitis,we
willcallita‘timeofdayclock,’or‘TODclock’forshort.Buttheword‘clock’willmeanthistypeofbit.
Howquicklydoesthisclockgoonandoff?Thesedaysitiswelloverabilliontimespersecond,orseveralgigahertz.Thisisoneofthemaincharacteristicsthatcomputercompaniestellyouabouttoshowyouhowgreattheircomputersare.Whenyouseecomputersforsale,thespeedthattheyadvertiseisthespeedofitsclock.Thefasteracomputeris,themoreexpensiveitis,becauseitcandomorethingsinonesecond.Itisthespeedofthissinglebitgoingonandoffthatsetsthetempoforthewholecomputer.
Tomovedataviathebus,weneedfirsttoenabletheoutputofoneandonlyoneregister,sothatitselectricitycantravelthroughthebustotheinputsofotherregisters.Then,whilethedataisonthebus,wewanttoturnthesetbitofthedestinationregisteronandoff.Sincethedestinationregistercapturesthestateofthebusattheinstantthatthesetbitgoesoff,wewanttomakesurethatitgoesoffbeforeweturnofftheenablebitatthefirstregistertomakesurethattherearenoproblems.
Letusfirstattachalengthofwiretotheoutputoftheclock.Thiswilldelaytheelectricityslightly.Wewantitdelayedaboutonequarterofacycle.
Ifweshowtheoriginalclockoutput(clk)andthedelayedclockoutput(clkd)onagraph,theywilllooklikethis:
Nowwe’regoingtodosomethingfairlysimple.Wewilltaketheoriginalclockandthedelayedclock,andbothANDthemandORthemtocreatetwonewbits,likeso:
Oneofthenewbitsisonwheneither‘clk’or‘clkd’areon,andtheothernewbitisononlywhenboth‘clk’and‘clkd’areon.ThegraphoftheinputsandoutputsoftheANDandORgatesisshownhere.Theyarebothstillgoingonandoffregularly,butoneofthemisonforlongerthanitisoff,andtheotheroneisoffforlongerthanitison.Theontimeofthesecondisrightinthemiddleoftheontimeofthefirst.
Noticethattheyhavenames,‘clke,’whichstandsforclockenable,and‘clks,’whichstandsforclockset.Andwhatdoyouknow,thesetwobitshavetheperfecttimingtomoveabyteofdatafromoneregister,acrossthebus,andintoanotherregister.Justconnect‘clke’totheenablebitofthe‘from’register,andconnect‘clks’tothesetbitofthe‘to’register.
Hereisasingleon/offcycleofthesetwobits.
Ifyoulookatthetiminghere,thismeetsourrequirementsofneedingtofirstenabletheoutputofaregister,andthen,afterthedatahasalittletimetotraveldownthebus,toturnthesetbitofthedestinationregisteronandoffbeforeturningtheenablebitoffatthefirstregister.
Ofcourse,theseclockbitscannotjustbeconnecteddirectlytoeveryregister.Theremustbeothergatesinbetween,thatonlyallowoneregistertogetan
enableatanyonetime,andonlythedesiredregister(s)toreceiveaset.Butallenablesandsetsultimatelycomefromthesetwobitsbecausetheyhavetherighttiming.
Sincewewilluseclk,clkeandclksthroughoutthecomputer,thisisthediagramwewillusetoshowtheclock:
DOINGSOMETHINGUSEFUL
Let'ssaythatwewanttodosomethinguseful,likeaddingonenumbertoanothernumber.WehaveanumberinR0,andthereisanothernumberinR1thatwewanttoaddtothenumberinR0.Theprocessorwehavebuiltsofarhasalloftheconnectionstodothisaddition,butitwilltakemorethanoneclockcycletodoit.
Inthefirstclockcycle,wecanenableR1ontothebus,andsetitintoTMP.
InthesecondcyclewecanenableR0ontothebus,settheALUtoADD,andsettheanswerintoACC.
Inthethirdcycle,wecanenableACContothebus,andsetitintoRo.
WenowhavetheoldvalueofR0,plusR1inR0.Perhapsthisdoesn'tseemveryuseful,butitisoneofthekindofsmallstepsthatcomputersdo.Manysuchsmallstepsmakethecomputerseemtobeabletodoverycomplexthings.
Thusweseethatfortheprocessortodosomethinguseful,ittakesseveralsteps.Itneedstobeabletodoactionsinasequence.Weneedanotherpieceinsidethis'ControlSection.'
STEPBYSTEP
Thischapterintroducesanewpartcalledthe"Stepper."First,wewilldescribethecompletedstepper,showingexactlywhatitdoes.Afterthat,wewillseeexactlyhowitisbuilt.Ifyouhappentotrustyourauthorenoughtobelievethatsuchasteppercanbebuiltoutofgates,andyou'reinsuchahurrythatyouwanttoskipthe'howitisbuilt'partofthechapter,youmightstillunderstandthecomputer.
Hereisacompletestepper.
Ithastwoinputs.Oneiscalled'clk,'becausethisiswhereweconnectabitthatisgoingonandoff,suchasouroriginalclockbit.Theotherinputiscalled'reset,'whichisusedtoreturnthestepperbacktostepone.Foroutputs,ithasanumberofbits,eachofwhichwillcomeonforonecompleteclockcycle,andthenturnoff,oneaftertheother.Theoutputlabeled'Step1'turnsonforoneclockcycle,then'Step2'forthenextclockcycle,etc.Asteppercanbebuilttohaveasmanystepsasneededforanyparticulartaskyouwanttodo.Inthecaseofthiscomputerthatwearebuilding,sevenstepsaresufficient.Whenthelaststep(7)turnson,itstayson,andthestepperdoesn'tdoanythingelseuntiltheresetbitisturnedonbriefly,atwhichtimethestepsstartoveragainbeginningwith'Step1.'
Hereisagraphoftheinput'clk'bit,andtheoutputsofaseven-stepstepper.
Hereishowthestepperisbuilt.Itisdoneusingsomeofthesamememorybitsthatweusedtomakeregisters,buttheyarearrangedverydifferently.Wearenotgoingtostoreanythinginthesebits,wearegoingtousethemtocreateaseriesofsteps.
Thestepperconsistsofseveralmemorybitsconnectedinastring,withtheoutputofoneconnectedtotheinputofthenext.Hereisadiagramthatshowsmostofthestepper:
Firstlookattheseriesof‘M’memorybitsjustliketheonesthatweusedearlierinthebook.Inthispicture,therearetwelveofthemconnectedtogether,withtheoutputofoneconnectedtotheinputofthenext,allthewaydowntheline.Theinputtothefirstbitontheleftisconnectedtoaplacewheretheelectricityisalwayson,sowhenthesetbitofthat‘M’comeson,that‘M’willreceivethatonstate,andpassitthroughtoitsoutput.
Ifyoulookatthesetbitsofthese‘M’s,youwillseethatthesetbitsoftheevennumbered‘M’sareconnectedtoclk,andthesetbitsoftheoddnumbered‘M’s
areconnectedtothesameclockafteritgoesthroughaNOTgate.ThisnewbitthatismadebypassingclkthroughaNOTgatecanbecalled'notclk,'andwecanshowbothonthisgraph:
Sowhatwillhappenwiththisbunchofgates?Ifyouassumethatallofthe'M'sstartintheoffstate,andthenstart'clk'"ticking,"hereiswhatitwilldo.
Thefirsttime'clk'comeson,nothingwillhappen,becausethesetbitofthefirst'M'isconnectedto'notclk,'whichisoffwhen'clk'ison.When'clk'goesoff,'notclk'turnson,andthefirst'M'willcomeon,butnothingwillhappenatthesecond'M'becauseits'set'bitisconnectedto'clk,'whichisnowoff.When'clk'comesbackon,thesecond'M'willnowcomeon.Astheclockticks,the'on'thatentersthefirstmemorybitwillstepdowntheline,onebitforeachtimetheclockgoeson,andonebitforeachtimetheclockgoesoff.Thustwobitscomeonforeachclockcycle.
Now,turningtothefullstepperdiagrambelow,step1comesfromaNOTgateconnectedtotheoutputofthesecond'M.'Sinceall'M'sstartoff,step1willbeonuntilthesecond'M'comeson,atwhichtimesteplwillbeover.Fortheremainingsteps,eachonewilllastfromthetimeitsleftside'M'turnsonuntilthetimeitsrightside'M'turnson.TheANDgatesforsteps2-6havebothinputsonwhentheleft'M'ison,andtheright'M'isoff.Ifweconnecttheoutputofone'M'andtheNOToftheoutputofan'M'twospacesfartherontoanANDgate,itsoutputwillbeonforonecompleteclockcycle.Eachonecomesonwhenitsleftinputhascomeon,butitsrightinputhasnotyetcomeon.Thisgivesusaseriesofbitsthateachcomeonforoneclockcycleandthenturnoff.
Theonlythingmissinghereisthatthe'M'bitscomeonandstayon.Oncetheyareallon,thereisnomoreactiondespitetheclock'scontinuedticking.Soweneedawaytoresetthemalloffsowecanstartoveragain.Wehavetohaveawaytoturnofftheinputtothefirst'M,'andthenturnonallofthesetbitsatthesametime.Whenthathappens,the'offattheinputtothefirst'M'willtravelthroughallofthe'M'sasfastasitcango.Wewilladdanewinputcalled'reset,'whichwillaccomplishthesethings.
Whenweturn'reset'on,itmakestheinputtothefirst'M'bitazero,andturnsonallofthe'sets'atthesametimesothatthezerocantraveldownthelineof'M'sveryquickly.ResetisalsoORedwithsteplsothatsteplturnsonimmediately.Nowallofthebitsareoff,andwehavestartedanothersequence.Resetonlyneedstobeturnedonforafractionofoneclockcycle.
Torecap,thisisastepper.Ithastwoinputs:aclockandareset.Foroutputs,ithasanumberofbits,eachofwhichwillcomeonforoneclockcycle.Wecanactuallymakethisaslongasneeded,butforthepurposesofthisbook,asevenstagestepperwillbesufficient.Therewillbeonlyonestepperinourcomputer,wewillrepresentitwiththissimplifieddiagram.
WehaverelocatedtheResetbittotherightsideofthediagram,andconnectedittothelaststep(7,)sothatthestepperwillautomaticallyresetitself.Step7willnotbeonforverylong,however,becauseitshutsitselfoffassoonasthezerocangetthroughthestringof'M's.Thismeansthatstep7willnotlastlongenoughtobeusedforoneofourdatatransfersoverthebus.Allofthethingswewanttoaccomplishwilltakeplaceinsteps1through6.
EVERYTHING'SUNDERCONTROL
Withourclock,wehaveadrumbeattomakethingsgo.Ithasabasicoutput,andtwomorethataredesignedtofacilitatethemovementofthecontentsofregistersfromonetoanother.Withthestepper,wehaveaseriesofbitsthatcomeononeafteranother,eachforoneclockcycle.
RememberthediagramoftheCPUwesawafewchaptersback?Itshowedthebus,theALU,sixregistersandeventheotherhalfofthecomputer(theRAM)allconnectedupprettyneatly.Atleastallofthebusconnectionswerethere.Butalltheregisters,theRAM,theBus1andtheALUarecontrolledbywiresthatcomefromthatmysteriousboxlabeled'ControlSection'thatweknownothingaboutyet.Nowitistimetolookinsidethatbox.
Thisdrawingisthebeginningofthecontrolsectionofthecomputer.Atthetoparetheclockandthestepper.ThenallofthecontrolbitsfromtheregistersandRAMhavebeenbroughtheretogetherinoneplace,withallofthe'enable'bitsontheleft,andallofthe'set'bitsontheright.ThenwehaveconnectedtheoutputofanANDgatetoeach'enable'andeach'set'bit.OneinputofeachANDgateisconnectedtoeither'clke'forthe'enables'ontheleft,or'clks'forthe'sets'ontheright.Thus,ifweusetheotherinputofthoseANDgatestoselectanyofthoseregisters,the'enable'bitofalloftheitemsontheleftwillneverbeturnedonexceptduring'clke'time.Similarlyontheright,the'set'bitofanyof
thoseregisterswillonlybeturnedonduring'clks'time.
Thisissortofaswitchboard.Everythingweneedtomakethecomputerdosomethingisrighthereinoneplace.Allweneedtodoisconnectsomecontrolbitstosomestepsinanintelligentmanner,andsomethingusefulwillhappen.
DOINGSOMETHINGUSEFUL,REVISITED
Nowthatwehavethebeginningofourcontrolsection,wecanjustaddafewwires,andwewillbeabletodothesimpleadditionwepostulatedearlier,thatofaddingR1toR0.
Allwehavetodoto'dosomethinguseful,'likeaddingR1toR0,istoconnectafewwiresinthemiddle,asshowninthisdiagramwithstepsfour,fiveandsix.EachstepcausessomethingtohappentosomeofthepartsthatareshownintheCPUdiagram.Eachstepisconnectedtoone'enable'ontheleft,andone'set'ontheright,andthereforecausesoneparttoconnectitsoutputtothebus,andanotherparttosavewhatnowappearsatitsinput.StepfouriswiredtoR1'enable'andTMP'set.'StepfiveiswiredtoR0'enable,'andACC'set.'TheALU'op'bitsdonotneedanyconnectionssincethe'op'codeforADDis000.StepsixiswiredtoACC'enable'andR0'set.'
Duringstepfour,R1isenabledandTMPisset.ThecontentsofR1travelacrossthebus(intheCPUdiagram)andarecapturedbyTMP.
Duringstepfive,R0isenabledandACCisset.IfwewantedtodosomethingotherthanADD,thisisthestepwherewewouldturnontheappropriateALU'op'codebits.
Duringstepsix,ACCisenabledandR0isset.
Hereisagraphofthesteps,showingwheneachregistergetsenabledandset.
R0nowcontainsthesumoftheoriginalcontentsofR0plusR1.
Thisishowthecomputermakesthingshappeninatightlycontrolledballetofbitsandbytesmovingaroundinsidethemachine.
Instepseven,thestepperisresettostep1,wheretheprocessrepeats.Ofcourseitisnotveryusefultojustdothisadditionoverandoveragain,evenifyoustartoutwiththenumber1inbothR0andR1,R0willgetupto255prettyquickly.
Iftheclockinourcomputerticksonebilliontimeseverysecond,otherwiseknownasonegigahertz,andevenifweusemultipleclockcyclesto“dosomethinguseful”likethis,thatmeansthatthecomputercandosomethinglikethishundredsofmillionsoftimesinonesecond.Butwedon’twanttojustaddR1toR0overandoveragain.
PerhapsnowthatwehaveaddedR1toR0,wewanttostorethatnewnumbertoaparticularaddressinRAM,andR2happenstohavethataddressinit.Again,ourprocessorhasalloftheconnectionsnecessarytodothis,andagainitwilltakemorethanoneclockcycletodoit.Instep4,wecanmoveR2acrossthebustoMAR.Instep5wecanmoveR0acrossthebustoRAM.That'sallthatisneeded,justtwoclockcyclesandwe'redone.
Thewiringforthisoperationissimplerthantheotherone,justtwoenablesandtwosets.
TherearemanycombinationsofthingsthatwecandowiththeRAM,thesixregistersandtheALU.WecouldgetabytefromRAMandmoveittoanyofthefourregisters,wecouldmoveanyoneortwooftheregistersthroughtheALUandADDthem,ANDthem,ORthem,XORthem,etc.
WeneedawayforourCPUtodoonethingonetime,andadifferentthingthenexttime.Thecontrolsectionneedssomethingtotellitwhattodoineachsequence.
WHAT'SNEXT?
Nowhere'sascaryidea.Imaginethatthejobthatanemployeedoesatafastfoodrestaurantgetsbrokendownintoitsindividualelements.Walktothecounter,say"MayItakeyourorder?"listentotheanswer,pressthe"cheeseburger"buttononthecashregister,etc.Nowletssaythatthereare256orlessindividualactionsinvolvedinthejobofworkingatsuchanestablishment.Youcouldtheninventacodethatwouldassociateoneofthestatesofabytewitheachoftheindividualactivitiesofanemployee.Thenyoucouldexpressthesequenceofanemployee'sactionsasasequenceofbytes.
Firstwemakeupacodetable.Wewritesomecodesdowntheleftsideofthepage.Thenwedecidewhatwewantthosecodestomean,andwritethosemeaningsnexttothecodes.Nowwehavealistofallofthepossibleactionsthatanemployeemighttake,andacodethatrepresentseachoneofthem:
00000000=Walktothecounter
00000001=Say"MayItakeyourorder?"
00000010=Listentotheanswer
00000011=Pressthecheeseburgerbutton
00000100=Pressthefriesbutton.
00000101=Pressthemilkbutton
00000110=Pressthetotalbutton
00000111=Collectthemoney
00001000=Givethecustomerthechange
00001001=Openanemptybag
00001010=Placeacheeseburgerinthebag
00001011=Placefriesinthebag
00001100=Placeamilkcontainerinthebag
00001101=Handthebagtothecustomer
10000000=Gotothestepnumberintheright6bits.
01000000=If"yes,"gotothestepnumberintheright6bits.
00010000=Gohome.
Nowifwewanttodescribehowtheemployeeissupposedtoact,wewriteasequenceofeventsthatheshouldfollow:
1.00000000=Walktothecounter.
2.00000001=Say"MayItakeyourorder?"
3.01000010=Ifcustomerisnotanswering,gotostep2.
4.00000010=Listentotheanswer.
5.01000111=Ifcustomerdoesn'tsaycheeseburger,gotostep7.
6.00000011=Pressthecheeseburgerbutton.
7.01001001=Ifcustomerdoesnotsayfries,gotostep9.
8.00000100=Pressthefriesbutton.
9.01001011=Ifcustomerdoesnotsaymilk,gotostep11.
10.00000101=Pressthemilkbutton.
11.01001101=Ifthecustomersaysthat'sall,gotostep13.
12.10000100=Gobacktostep4.
13.00000110=Pressthetotalbutton.
14.00000111=Collectthemoney.
15.00001000=Makechangeandgiveittothecustomer.
16.00001001=Openanemptybag.
17.01010011=Iforderdoesn'tincludecheeseburger,gotostep19.
18.00001010=Placeacheeseburgerinthebag.
19.01010110=Iforderdoesnotincludefries,gotostep22.
21.00001011=Placefriesinthebag.
22.01011000=Iforderdoesnotincludemilk,gotostep24.
23.00001100=Placeamilkcontainerinthebag.
24.00001101=Handthebagtothecustomer.
25.01011011=Ifitisquittingtime,gotostep27.
26.10000001=Gobacktostep1.
27.00010000=Gohome.
Ihopenobodyevertriestomaketheemployeesofafastfoodrestaurantlearnacodelikethis.Peopledon'ttakewelltobeingsomechanized.Butmaybesomeonewilltrytostaffoneoftheserestaurantswithrobotssomeday.Inthatcase,therobotswouldprobablyworkbetterusingthissortofacode.
Andourcomputermightbeableto'understand'acodelikethis.
THEFIRSTGREATINVENTION
Whatweneedissomewaytododifferentoperationsfromonesteppersequencetothenext.Howcouldwehaveitwireduponewayforonesequence,andthenadifferentwayforthenextsequence?Theanswer,ofcourse,istousemoregates.ThewiringforoneoperationcanbeconnectedordisconnectedwithANDgates,andthewiringforadifferentoperationcanbeconnectedordisconnectedwithsomemoreANDgates.Andtherecouldbeathirdandfourthpossibilityormore.Aslongasonlyoneofthoseoperationsisconnectedatonetime,thiswillworkfine.Nowwehaveseveraldifferentoperationsthatcanbedone,buthowdoyouselectwhichonewillbedone?
Thetitleofthischapteris"TheFirstGreatInvention,"sowhatistheinvention?TheinventionisthatwewillhaveaseriesofinstructionsinRAMthatwilltelltheCPUwhattodo.Weneedthreethingstomakethiswork.
Thefirstpartoftheinventionis,thatwearegoingtoaddanotherregistertotheCPU.Thisregisterwillbecalledthe"InstructionRegister,"or"IR"forshort.Thebitsfromthisregisterwill"instruct"theCPUwhattodo.TheIRgetsitsinputfromthebus,anditsoutputgoesintothecontrolsectionoftheCPUwherethebitsselectoneofseveralpossibleoperations.
ThesecondpartoftheinventionisanotherregisterintheCPUcalledthe"InstructionAddressRegister,"or"IAR"forshort.Thisregisterhasitsinputandoutputconnectedtothebusjustlikethegeneralpurposeregisters,butthisoneonlyhasonepurpose,andthatistostoretheRAMaddressofthenextinstructionthatwewanttomoveintotheIR.IftheIARcontains00001010(10decimal,)thenthenextinstructionthatwillbemovedtotheIRisthebyteresidingatRAMaddressten.
Thethirdpartoftheinventionissomewiringinthecontrolsectionthatusesthesteppertomovethedesired"instruction"fromRAMtotheIR,add1totheaddressintheIARanddotheactioncalledforbytheinstructionthathasbeenputintheIR.Whenthatinstructioniscomplete,thestepperstartsoveragain,butnowtheIARhashad1addedtoit,sowhenitgetsthatinstructionfromRAM,itwillbeadifferentinstructionthatwaslocatedatthefollowingRAMaddress.
Theresultofthesethreepartsisagreatinvention.Thisiswhatallowsustomakethecomputerdomanydifferentthings.Ourbus,ALU,RAMandregistersmakemanycombinationspossible.ThecontentsoftheIRwilldeterminewhatregistersaresenttowhere,andwhatkindofarithmeticorlogicwillbedone
uponthem.AllwehavetodoistoplaceaseriesofbytesinRAMthatrepresentaseriesofthingsthatwewanttodo,oneafteranother.
ThisseriesofbytesresidinginRAMthattheCPUisgoingtomakeuseofiscalleda"program."
ThebasicthingthathappenshereisthattheCPU"fetches"aninstructionfromRAM,andthen"executes"theinstruction.Thenitfetchesthenextoneandexecutesit.Thishappensoverandoverandover,millionsorbillionsoftimeseverysecond.Thisisthesimplicityofwhatacomputerdoes.SomeoneputsaprograminRAM,andthatprogram,ifintelligentlydesigned,makesthecomputerdosomethingthatpeoplefinduseful.
Thestepperinthiscomputerhassevensteps.Thepurposeofstep7isonlytoresetthestepperbacktostep1.SotherearesixstepsduringwhichtheCPUdoessmallthings.Eachsteplastsforoneclockcycle.Thesixstepstakenasawholeiscalledan"InstructionCycle."IttakessixstepsfortheCPUtodoalloftheactionsnecessarytofetchandexecuteoneinstruction.Ifweassumethatourclockticksatonegigahertz,thenourcomputerwillbeabletoexecute166,666,666instructionseverysecond.
HereisthepictureoftheCPUwiththetwonewregistersaddedtoit.TheretheyareundertheControlSection,connectedtothebus.TheIARhasa'set'and'enable,'theIRonlyhasa'set,'justlikeTMPandMARbecausetheiroutputsarenotconnectedtothebus,soweneverneedtoturnthemoff.
BelowisthewiringwithintheControlSectionthatdoesthe'fetch'partofthe
instructioncycle.Itusesthefirstthreestepsofthestepperandisthesameforalltypesofinstructions.
Thestepper'sfirstthreestepsareshownhere,andresultin'fetching'thenext'instruction'fromRAM.Thentherestofthesteps'execute'the'instruction.'Exactlywhatwillbedoneinsteps4,5and6,isdeterminedbythecontentsoftheinstructionthatwasfetched.Thenthestepperstartsover,fetchesthenextinstruction,andexecutesit.
ThebottomofthisdiagramincludestheInstructionRegister.NoticethatwehavegivennumberstotheindividualbitsoftheIR,oattheleftthrough7ontheright.Wewillbereferringtotheindividualbitssoon.
Herearethedetailsofexactlyhowsteps1,2and3resultinfetchinganinstructioninourlittlecomputer:
Step1isthemostcomplicatedbecauseweactuallyaccomplishtwothingsatthesametime.ThemainthingwewanttodoistogettheaddressinIARovertoMAR.ThisistheaddressofthenextinstructionthatwewanttofetchfromRAM.Ifyoulookatthewirecomingoutofstep1ofthestepper,youcanseethattwooftheplacesitisconnectedtoarethe'enable'ofIARandthe'set'ofMAR.Thus,thecontentsofIARwillbeplacedonthebusduring'clke'andsetintoMARduring'clks.'Sometimeduringtheinstructioncycle,weneedtoadd1tothevalueinIAR,andsinceIARisalreadyonthebus,wemightaswelldoitnow.Ifwedon'tsendanythingtotheALU's'op'bits,theywillallbezero,andsince000isthecodeforADD,theALUwillbedoinganADDoperationon
whateverisonitstwoinputs,andpresentingtheanswertoACC.Oneinputcomesfromthebus,whichhasIARonitduringthistime.Ifwealsoturnonthe'bus1'bitduringstep1,theotherinputtotheALUwillbeabytewiththebinaryvalueof1.Ifweturnonthe'set'ofACCduring'clks,'wewillcapturethesumofIARplus1inACC.Thisjusthappenstobetheaddressoftheinstructionthatwewillwanttofetchafterwearedonewiththecurrentone!
Step2enablesthecurrentlyselectedbyteinRAMontothebus,andsetsitintoIR.Thisistheinstructionthatwewill'execute'insteps4,5and6ofthisinstructioncycle.Inthediagram,youcanseethatthewirecomingfromstep2isconnectedtothe'enable'ofRAMandthe'set'ofIR.
Instep3,weneedtofinishupdatingIAR.Weadded1toitinstep1,buttheanswerisstillinACC.ItneedstobemovedtoIARbeforethebeginningofthenextinstructioncycle.Soyoucanseethewirecomingoutofstep3isconnectedto'enable'ofACCand'set'ofIAR.
Bythetimewegettostep4,theinstructionhasalreadybeenmovedfromRAMtoIR,andnowsteps4,5and6canthendowhateveriscalledforbythecontentsofIR.Whenthatoperationisdoneandthestepperisreset,thesequencewillstartoveragain,butnowIARhashad1addedtoit,sotheinstructionatthenextRAMaddresswillbefetchedandexecuted.
ThisideaofputtingaseriesofinstructionsinRAMandhavingtheCPUexecutethemisagreatinvention.
INSTRUCTIONS
Wenowhavethisnewregister,calledtheInstructionRegister,whichcontainsabytethatisgoingtotelltheControlSectionwhattodo.Thepatternsthatareputintothisregisterhaveameaning.Soundslikeanothercode,andindeed,itis.Thiscodewillbecalledthe"InstructionCode."
Sincewearebuildingthiscomputerfromscratch,wegettoinventourowninstructioncode.Wewilltakethe256differentcodesthatcanbeputintheInstructionRegister,anddecidewhattheywillmean.Thenwehavetodesignthewiringinsidethecontrolunitthatwillmaketheseinstructionsdowhatwesaidtheywoulddo.
Doyourememberthebinarynumbercode?Wesaidthatitwastheclosestthingtoa'natural'computercodebecauseitwasbasedonthesamemethodweuseforournormalnumbersystem.ThentherewastheASCIIcode,whichwasjustinventedbyabunchofpeopleatameeting.ThereisnothingnaturalaboutASCIIatall,itwasjustwhatthosepeopledecideditwouldbe.
NowwehavetheInstructionCode,whichwillalsobeatotallyinventedcode-nothingnaturalaboutit.Manydifferentinstructioncodeshavebeeninventedformanydifferenttypesofcomputers.Wewillnotstudyanyofthemhere,norwillyouneedtostudyanyofthemlater,unlessyouaregoingtogoontoahighlytechnicalcareerwherethatisnecessary.ButallInstructionCodesaresimilar,inthattheyarewhatmakethecomputerwork.TheonlyInstructionCodeinthisbookwillbeonethatweinventforoursimplecomputer.ThemostimportantthingininventingourInstructionCode,willbehowsimplewecanmakethewiringthatwillmakethecodework.
Howmanydifferentinstructionscouldtherebe?Sincetheinstructionregisterisabyte,theremightbeasmanyas256differentinstructions.Fortunately,wewillonlyhaveninetypesofinstructions,andall256combinationswillfallintooneofthesecategories.Theyareprettyeasytodescribe.
Allinstructionsinvolvemovingbytesacrossthebus.TheinstructionswillcausebytestogotoorfromRAM,toorfromregisters,andsometimesthroughtheALU.Inthefollowingchapters,foreachtypeofinstruction,wewilllookatthebitsofthatinstruction,thegatesandwiringnecessarytomakeitwork,andanotherhandycodewecanusetomakewritingprogramseasier.
THEARITHMETICORLOGICINSTRUCTION
ThisfirsttypeofinstructionisthetypethatusestheALUlikeourADDoperationearlier.Asyourecall,theALUhaseightthingsitcando,andforsomeofthosethingsitusestwobytesofinput,forotherthingsitonlyusesonebyteofinput.Andinsevenofthosecases,ithasonebyteofoutput.
ThistypeofinstructionwillchooseoneoftheALUoperations,andtworegisters.Thisisthemostversatileinstructionthatthecomputercando.Itactuallyhas128variations,sincethereareeightoperations,andfourregisters,andyougettochoosetwicefromthefourregisters.Thatiseighttimesfourtimesfour,or128possiblewaystousethisinstruction.Thusthisisnotjustoneinstruction,butratheritisawholeclassofinstructionsthatallusethesamewiringtogetthejobdone.
HereistheInstructionCodefortheALUinstruction.IfthefirstbitintheInstructionRegisterisa1,thenthisisanALUinstruction.That’sthesimplicityofit.Ifthefirstbitison,thenthenextthreebitsintheinstructiongetsenttotheALUtotellitwhattodo,thenexttwobitschooseoneoftheregistersthatwillbeused,andthelasttwobitschoosetheotherregisterthatwillbeused.
Therefore,theALUInstruction(1),toadd(000)Register2(10)andRegister3(11),andplacetheanswerinRegister3,wouldbe:10001011.Ifyouplacedthiscode(10001011)inRAMataddress10,andsettheIARto10,andstartedthecomputer,itwouldfetchthe10001011fromaddress10,placeitinIR,andthenthewiringinthecontrolsectionwoulddotheadditionofR2andR3.
Ifyouchooseaoneinputoperation,suchasSHL,SHRorNOT,thebytewillcomefromtheRegA,gothroughtheALU,andtheanswerwillbeplacedintheRegB.YoucanchoosetogofromoneregistertoanothersuchasR1toR3,orchoosetogofromoneregisterbackintothesameone,suchasR2toR2.Whenyoudothelatter,theoriginalcontentsoftheregisterwillbereplaced.
Fortwoinputoperations,RegAandRegBwillbesenttotheALU,andtheanswerwillbesenttoRegB.SowhateverwasinRegB,whichwasoneoftheinputstotheoperation,willbereplacedbytheanswer.Youcanalsospecifythesameregisterforbothinputs.Thiscanbeuseful,forinstance,ifyouwanttoputallzerosinRegister1,justXORR1withR1.NomatterwhatisinR1tobeginwith,allbitcomparisonswillbethesame,whichmakestheoutputofallbitszeros,whichgetsplacedbackintoR1.
TheCMPoperationtakestwoinputsandcomparesthemtoseeiftheyareequal,andifnot,ifthefirstoneislarger.ButtheCMPoperationdoesnotstoreitsoutputbyte.Itdoesnotreplacethecontentsofeitherinputbyte.
ThewiringintheControlunitfortheALUinstructionisprettysimple,butthereisoneextrathingthatwillbeusedbymanytypesofinstructionsthatweneedtolookatfirst.Thishastodowiththeregisters.In"DoingSomethingUsefulRevisited,"weusedtworegisters.Tousethem,wejustconnectedtheANDgateforeachregistertothedesiredstepofthestepper.Thiswasfine,butintheALUinstruction,andmanyothers,therearebitsintheinstructionregisterthatspecifywhichregistertouse.Thereforewedon'twanttowireupdirectlytoanyoneregister,weneedtobeabletoconnecttoanyoftheregisters,butletthebitsintheinstructionchooseexactlywhichone.HereistheControlSectionwiringthatdoesit:
Lookattherightsidefirst.Whenwewanttosetageneral-purposeregister,weconnectthepropersteptothiswirethatwewillcall'RegB.'Asyoucansee,'elks'isconnectedtoallfourANDgates.'RegB'isalsoconnectedtoallfourANDgates.ButthesefourANDgateseachhavethreeinputs.ThethirdinputtoeachANDgatecomesfroma2x4decoder.Yourememberthatoneandonlyoneoutputofadecoderisonatanygiventime,soonlyoneregisterwillactuallybeselectedtohaveits'set'bitturnedon.TheinputtothedecodercomesfromthelasttwobitsoftheIR,sotheydeterminewhichoneregisterwillbesetbythiswirelabeled'RegB.'IfyoulookbackatthechartofthebitsoftheALUInstructionCode,itshowsthatthelasttwobitsoftheinstructionarewhatdeterminewhichregisteryouwanttouseforRegB.
Theleftsideofthepictureisverymuchliketherightside,exceptthattherearetwoofeverything.RememberthatinanALUinstructionsuchasADD,weneedtoenabletworegisters,oneatatime,fortheinputstotheALU.Thelasttwobitsoftheinstructionarealsousedfor'RegB'ontheleft,andyoucanseethat'elke,''RegB'andadecoderareusedtoenableoneregisterduringitsproperstep.Bits4and5oftheIRareusedtoenable'RegA'duringitsproperstep,usingaseparatedecoderandawirecalled'RegA'TheoutputsofthesetwostructuresareORedtogetherbeforegoingtotheactualregisterenablebits.Wewillneverselect'RegA'and'RegB'atthesametime.
Whathappenswhentheinstructionthathasbeenfetchedbeginswithal?ThatmeansthatthisisanALUinstruction,andweneedtodothreethings.Firstwe
wanttomove'RegB'toTMP.ThenwewanttotelltheALUwhichoperationtodo,put'RegA'onthebusandsettheoutputoftheALUintoACC.ThenwewanttomoveACCto'RegB.'
BitooftheIRistheonethatdeterminesifthisisanALUinstruction.WhenBitoison,thethingsthatBitoiswireduptomakeallofthestepsofanALUinstructionoccur.
ThenextdiagramshowstheeightgatesandthewiresthatareaddedtotheControlSectionthatmakesteps4,5and6ofanALUinstructiondowhatweneedthemtodo.
Inthediagrambelow,justaboveandtotheleftoftheIR,therearethreeANDgates.Theoutputsofthesegatesgotothethree'op'wiresontheALUthattellitwhichoperationtodo.EachofthesethreeANDgateshasthreeinputs.OneinputofeachgateiswiredtobitooftheIR.Asecondinputofeachgateiswiredtostep5fromthestepper.Theremaininginputofeachgateiswiredtobits1,2and3oftheIR.
Therefore,thethreewiresthatgototheALUwillbe000atalltimesexceptduringstep5whenIRbitohappenstobea1.Atsuchatime,thewiresgoingtotheALUwillbethesameasbits1,2and3oftheIR.
IRbitocontinuesupthediagram,turnsrightandisconnectedtoonesideofthreemoreANDgates.TheothersidesofthesegatesareconnectedtoSteps4,5and6.
Theoutputofthefirstgatecomesonduringstep4,andyoucanseeitgoingtotwoplaces.Ontheleft,itenables'RegB'ontothebus,andontheright,itsetsthebusintoTMP.ThisstepisactuallynotnecessaryfortheSHL,SHRandNOToperations,butitdoesn'tharmanything,anditwouldbefairlycomplicatedtogetridof,soforsimplicity'ssakewe'lljustleaveitthisway.
Thesecondgatecomesonduringstep5(thesamestepthattheALUgetsitsorders),andgoingtotheleftisawirethatenables'RegA'ontothebus.TheALUnowhasoneinputinTMP,theotherinputonthebus,anditsoperationspecifiedbythosethree'op'wires,soontherightisawirethatsetstheanswerintoACC.
Thethirdgateturnsonduringstep6.ThewiregoingtotheleftenablesACContothebus,andthewiregoingtotherightsetsthebusinto'RegB.'
ThereisjustonespecialsituationinanALUinstruction,andthatiswhentheoperationisCMP,code111.Foracompareoperation,wedonotwanttostoreanyresultsbackinto'RegB.'Therefore,thereisathreeinputANDgateconnectedtoIRbits1,2and3,whichisthenconnectedtoaNOTgate,andthentoathirdinputontheANDgatethatdoesstep6oftheALUinstruction.Sowhentheoperationis111,thefirstANDwillcomeon,theNOTwillgooff,andtheoutputoftheStep6ANDgatewillnotturnon.
ThisALUinstructionisnowdone.Step7resetsthestepper,whichthengoesthroughitsstepsagain,fetchingthenextinstruction,etc,etc.
Wearegoingtoinventonemorethinghere,andthatisashorthandwayofwritingCPUinstructionsonapieceofpaper.IntheInstructionCode,10001011means"AddR2toR3,"butittakesalotofpracticeforapersontolookat10001011andimmediatelythinkofadditionandregisters.Italsowouldtakealotofmemorizationtothinkofittheotherwayaround,thatis,ifyouwantedtoXORtworegisters,whatistheInstructionCodeforXOR?ItwouldbeeasiertowritesomethinglikeADDR2,R3orXORR1,R1.
Thisideaofusingashorthandhasaname,anditiscalledacomputerlanguage.Soalongwithinventinganinstructioncode,wewillalsoinventacomputerlanguagethatrepresentstheinstructioncode.TheALUinstructionresultsinthefirsteightwordsofournewlanguage.
Whenapersonwantstowriteacomputerprogram,hecanwriteitdirectlyintheinstructioncode,oruseacomputerlanguage.Ofcourse,ifyouwriteaprograminacomputerlanguage,itwillhavetobetranslatedintotheactualinstructioncodebeforeitcanbeplacedinRAMandexecuted.
THELOADANDSTOREINSTRUCTIONS
TheLoadandStoreinstructionsareprettysimple.TheymoveabytebetweenRAMandaregister.Theyareverysimilartoeachothersowewillcoverbothoftheminonechapter.
We'llgettothedetailsoftheseinstructionsinamoment,butfirstweneedtohavesomethingthattellsuswhenwehaveaLoadorStoreinstructionintheInstructionRegister.WiththeALUinstruction,allweneededtoknowwasthatbitowason.Thecodeforeveryothertypeofinstructionbeginswithbitooff,soifweconnectaNOTgatetobito,whenthatNOTgateturnson,thattellsusthatwehavesomeothertypeofinstruction.Inthiscomputer,thereareeighttypesofinstructionsthatarenotALUinstructions,sowhenbitoisoff,wewillusethenextthreebitsoftheIRtotellusexactlywhichtypeofinstructionwehave.
ThethreebitsthatwenttotheALUinanALUinstructionalsogotoa3x8decoderhereintheControlSection.Asyouremember,oneandonlyoneoftheoutputsofadecoderisonatalltimes,sowewillhaveANDgatesontheoutputstopreventanyoutputfromgoinganywhereduringanALUinstruction.ButwhenitisnotanALUinstruction,theoneoutputofthedecoderthatison,willgetthroughitsANDgate,andinturnwillbeconnectedtosomemoregatesthatmaketheappropriateinstructionwork.
Inthediagrambelow,youcanseeIRbits1,2and3goingintoadecoderwhichhaseightANDgatesonitsoutputs.IRbitohasaNOTgatewhichgoestotheothersideofthoseeightANDgates.Thisdecoderisusedfortherestoftheinstructionsthatourcomputerwillhave.
Thischapterisabouttheinstructionsthatusethefirsttwooutputsofthedecoder,theonesthatcomeonwhentheIRstartswith0000or0001.
ThefirstinstructionmovesabytefromRAMtoaregister,thisiscalledthe"Load"instruction.Theotheronedoesthesameinreverse,itmovesabytefromaregistertoRAM,andiscalledthe"Store"instruction.
TheInstructionCodefortheLoadinstructionis0000,andfortheStoreinstructionis0001.Theremainingfourbitsinbothcasesspecifytworegisters,justliketheALUinstructiondid,butinthiscase,oneregisterwillbeusedtoselectoneofthelocationsinRAM,andtheotherregisterwilleitherbeloadedfrom,orstoredto,thatRAMlocation.
Step4isthesameforbothinstructions.OneoftheregistersisselectedbyIRbits4and5andisenabledontobus.ThebusisthensetintoMAR,thusselectingoneaddressinRAM.
Instepfive,IRbits6and7selectanotheroneoftheCPUregisters.FortheLoadinstruction,RAMisenabledontothebusandthebusissetintotheselectedregister.FortheStoreinstruction,theselectedregisterisenabledontothebusandthebusissetintoRAM.
Eachoftheseinstructionsonlyneedtwostepstocomplete,step6willdonothing.
Herearetwonewwordsforourcomputerlanguage:
THEDATAINSTRUCTION
Nowhereisaninterestinginstruction.AllitdoesisloadabytefromRAMintoaRegisterliketheLoadinstruction,above.Thethingthatisdifferentaboutitthough,iswhereinRAMitwillgetthatbyte.
IntheDatainstruction,thedatacomesfromwherethenextinstructionoughttobe.Soyoucouldconsiderthatthisinstructionisactuallytwobyteslong!Thefirstbyteistheinstruction,andthenextbyteissomedatathatwillbeplacedintoaregister.Thisdataiseasytofind,becausebythetimewehavetheinstructionintheIR,theIARhasalreadybeenupdated,andsoitpointsrighttothisbyte.
HereistheInstructionCodefortheDatainstruction.Bitsoto3are0010.Bits4and5arenotused.Bits6and7selecttheregisterthatwillbeloadedwiththedatathatisinthesecondbyte.
Allthisinstructionneedstodois,instep4,sendIARtoMAR,andinstep5,sendRAMtothedesiredCPUregister.However,thereisonemorethingthatneedstohappen.Sincethesecondbyteoftheinstructionisjustdatathatcouldbeanything,wedonotwanttoexecutethissecondbyteasaninstruction.Weneedtoadd1totheIARasecondtimesothatitwillskipthisbyteandpointtothenextinstruction.Wewilldothisthesamewaythatitisdoneinsteps1and3.Instep4,whenwesendIARtoMAR,wewilltakeadvantageofthefactthattheALUiscalculatingIARplussomethingatthesametime,wewillturnonthe'Bus1,'andsettheanswerintoACC.Step5stillmovesthedatatoaRegister,andinstep6wecanmoveACCtoIAR.
Hereisanothernewwordforourcomputerlanguage:
THESECONDGREATINVENTION
ThefirstgreatinventionisthisideaofhavingastringofinstructionsinRAMthatgetexecutedonebyonebytheCPU.Butourclockisveryfast,andtheamountofRAMwehaveislimited.Whatwillhappen,infarlessthanasecond,whenwehaveexecutedeveryinstructioninRAM?
Fortunately,wewillnothavetoanswerthatquestion,becausesomeonecameupwithanothertypeofinstructionthatissoimportantthatitqualifiesasthesecondgreatinventionnecessarytoallowthecomputertodowhatitdoes.BecauseoftheversatilearrangementofourCPUanditsControlSection,itisanextremelysimplethingtomakethiswork,butitsimportanceshouldnotbelostbecauseofthissimplicity.
ThisnewtypeofinstructioniscalledaJumpinstruction,andallitdoesistochangethecontentsoftheIAR,thuschangingwhereinRAMthenext,andsubsequentinstructionswillcomefrom.
TheexacttypeofJumpinstructiondescribedinthischapteriscalleda"JumpRegister"instruction.ItsimplymovesthecontentsofRegBintotheIAR.HereistheInstructionCodeforit:
ThecomputerisexecutingaseriesofinstructionsinRAM,oneaftertheother,andsuddenlyoneofthoseinstructionschangesthecontentsoftheIAR.Whatwillhappenthen?Thenextinstructionthatwillbefetchedwillnotbetheonethatfollowsthelastone.ItwillbetheonethatisatwhateverRAMaddresswas
loadedintotheIAR.Anditwillcarryonfromthatpointwiththenextone,etc.untilitexecutesanotherjumpinstruction.
ThewiringfortheJumpRegisterinstructiononlyneedsonestep.Instep4,theselectedregisterisenabledontothebus,andsetintotheIAR,andthatisall.IfwewantedtospeedupourCPU,wecouldusestep5toresetthestepper.Buttokeepourdiagramsimple,wewon’tbotherwiththat.Steps5an6willdonothing.
Hereisanothernewwordforourcomputerlanguage:
ANOTHERWAYTOJUMP
ThisisanothertypeofJumpinstruction.ItissimilartotheDatainstructioninthatitusestwobytes.ItreplacestheIARwiththebytethatisinRAMimmediatelyfollowingtheinstructionbyte,thuschangingwhereinRAMthenextandsubsequentinstructionswillcomefrom.HereistheInstructionCodeforit.Bits4,5,6and7arenotusedinthisinstruction:
ThisexacttypeofJumpinstructionisjustcalleda"Jump."Itisusefulwhenyouknowtheaddressthatyouaregoingtowanttojumpto,whenyouarewritingtheprogram.TheJumpRegisterInstructionismoreusefulwhentheaddressyouaregoingtowanttojumptoiscalculatedastheprograminrunning,andmaynotalwaysbethesame.
OneofthethingsyoucandowithaJumpinstructionistocreatealoopofinstructionsthatexecuteoverandoveragain.YoucanhaveaseriesoffiftyinstructionsinRAM,andthelastinstruction"Jumps"backtothefirstone.
LiketheDatainstruction,theIARalreadypointstothebyteweneed.UnliketheDataInstruction,wedon'tneedtoadd1totheIARasecondtimebecausewearegoingtoreplaceitanyway.Soweonlyneedtwosteps.Instep4,wesendIARtoMAR.Instep5wemovetheselectedRAMbytetotheIAR.Step6willdonothing.
Hereisthewiringthatmakesitwork:
Hereisanothernewwordforourcomputerlanguage:
THETHIRDGREATINVENTION
Hereisthethird,andlast,inventionthatmakesacomputeracomputer.
ThisisjustliketheJumpInstruction,butsometimesitjumps,andsometimesitdoesn't.Ofcourse,tojumpornottojumpisjusttwopossibilities,soitonlytakesonebittodeterminewhichwillhappen.Mostlywhatwearegoingtointroduceinthischapteriswherethatonebitcomesfrom.
Doyourememberthe'Carry'bitthatcomesoutof,andgoesbackintotheALU?Thisbitcomeseitherfromtheadder,orfromoneoftheshifters.Ifyouaddtwonumbersthatresultinanamountthatisgreaterthan255,thecarrybitwillcomeon.Ifyouleftshiftabytethathastheleftbiton,orrightshiftabytethathastherightbiton,thesesituationswillalsoturnontheALU'scarryoutbit.
ThereisalsoabitthattellsusifthetwoinputstotheALUareequal,anotheronethattellsusiftheAinputislarger,andonemorebitthattellsusiftheoutputoftheALUisallzeros.
ThesebitsaretheonlythingsthatwehavenotyetfoundahomeforintheCPU.Thesefourbitswillbecalledthe"Flag"bits,andtheywillbeusedtomakethedecisionfora"JumpIf"instructionastowhetheritwillexecutethenextinstructioninRAMorjumptosomeotheraddress.
Whatwearetryingtogetthecomputertobeabletoaccomplish,isforittofirstexecuteanALUinstruction,andthenhaveoneormore"JumpIf"instructionsfollowingit.The"JumpIfwilljumpornotdependingonsomethingthathappenedduringtheALUinstruction.
Ofcourse,bythetimethe"JumpIf"isexecuting,theresultsoftheALUinstructionarelonggone.IfyougobackandlookatthedetailsoftheALUinstruction,itisonlyduringstep5thatalloftheproperinputsaregoingintotheALUandthedesiredansweriscomingout.ItisatthistimethattheanswerissetintoACC.ThetimingisthesameforallfourFlagbits,theyareonlyvalidduringstep5oftheALUinstruction.Therefore,weneedawaytosavethestateoftheFlagbitsastheywereduringstep5oftheALUinstruction.
HereisthelastregisterthatwearegoingtoaddtotheCPU.ThiswillbecalledtheFLAGregister,andweareonlygoingtousefourbitsofit,oneforeachoftheflags.
TheFlagbitsfromtheALUareconnectedtotheinputofthisregister,anditwillbesetduringstep5oftheALUinstructionjustlikeACCanditwillstaysetthatwayuntilthenexttimeanALUinstructionisexecuted.ThusifyouhaveanALUinstructionfollowedbya“JumpIf”instruction,the“Flag”bitscanbeusedto“decide”whethertoJumpornot.
EveryinstructioncycleusestheALUinstep1toadd1totheaddressforthenextinstruction,butonlystep5oftheALUinstructionhasaconnectionthatsetstheFlags.(WedidnotshowthisconnectioninthewiringfortheALUinstructionbecausewehadnotyetintroducedtheFlagReg,butitwillappearinthecompletedControlSectiondiagram.)
ThiscombinationofFlagbits,andtheJumpIFinstruction,isthethirdandlastgreatinventionthatmakescomputersasweknowthemtoday,work.
HereistheInstructionCodefora‘JumpIf’instruction.ThesecondfourbitsoftheinstructiontelltheCPUwhichflagorflagsshouldbechecked.Youputa‘1’intheinstructionbit(s)correspondingtotheflag(s)thatyouwanttotestfor.IfanyoneoftheFlagsthatyoutestison,thejumpwillhappen.Thisarrangementgivesusanumberofwaystodecidewhethertojumpornot.Thereisasecondbytethatcontainstheaddresstojumpto,ifthejumpistaken.
HereisthewiringintheControlSectionthatmakestheJumpIfinstructionwork.
Step4movesIARtoMARsowearepreparedtogetthe'JumptoAddress'thatwewilluseIFwejump.Butbecausewemightnotjump,wealsoneedtocalculatetheaddressofthenextinstructioninRAM.Andsostep4alsoturnsonBus1andsetstheanswerinACC.
Instep5,wemoveACCtoIARsowearereadytofetchthenextinstructionIFwedon'tjump.
Step6iswherethe"decision"ismade.WewillmovethesecondbyteoftheinstructionfromRAMtoIARIFthethirdinputtothatANDgateison.ThatthirdinputcomesfromanORgatewithfourinputs.ThosefourinputscomefromthefourFlagbitsafterbeingANDedwiththelastfourbitsoftheJumpIf
instructioninIR.If,forinstance,thereisa'1'inthe'Equal'bitoftheinstruction,andthe'Equal'Flagbitison,thenthejumpwilloccur.
Herearemorewordsforourcomputerlanguage.'J'meansJump,'CmeansCarry,A'meansAislarger,'E'meansAEqualsBand'Z'meansthattheanswerisallZeros.HerearethewordsofthelanguagethattestasingleFlag:
Youcanalsotestmorethanoneflagbitatthesametimebyputtinga1inmorethanoneofthefourbits.Actuallysincetherearefourbits,thereare16possiblecombinations,buttheonewithallfourbitsoffisnotusefulbecauseitwillneverjump.Forthesakeofcompleteness,herearetherestofthepossibilities:
THECLEARFLAGSINSTRUCTION
Thereisoneannoyingdetailthatweneedtohavehere.Whenyoudoadditionorshifting,youhavethepossibilityofgettingthecarryflagturnedonbytheoperation.Thisisnecessary,weuseitfortheJumpIfinstructionasinthepreviouschapter.
TheCarryFlagisalsousedasaninputtotheadditionandshiftoperations.Thepurposeofthisissoyoucanaddnumberslargerthan255andshiftbitsfromoneregistertoanother.
Theproblemthatarisesisthatifyouarejustaddingtwosingle-bytenumbers,youdon'tcareaboutanypreviousCarry,buttheCarryFlagmaystillbesetfromapreviousoperation.Inthatcase,youmightadd2+2andget5!
Biggercomputershaveseveralwaystodothis,butforus,wewilljusthaveaClearFlagsInstructionthatyouneedtousebeforeanyaddsorshiftswhereanunexpectedcarrybitwouldbeaproblem.
HereistheInstructionCodeforthisinstruction.Bits4,5,6and7arenotused.
Thewiringforthisisverysimpleandabittricky.Wewillnotenableanythingontothebus,thusitandthe'A'ALUinputwillbeallzeros.Wewillturnon'Bus1'sothe'B'inputis00000001.Wewon'tsendanoperationtotheALU,soitwillbeinADDmode.TheALU,therefore,willbeadding0and1,andtheremaybeacarryinput.Theanswerthenwillbeeither00000001or00000010.Buttherewillbenocarryoutput,theanswerisnotzeroandBislargerthanAso'equal'and'Alarger'willbothbeoff.We'set'theFlagRegatthistimewhileallfourFlagbitsareoff.
Hereisanotherwordforourlanguage.
TADAA!
WehavenowwireduptheControlSectionofourCPU.Asaresult,wecanplaceaseriesofinstructionsinRAM,andtheClock,Stepper,InstructionRegisterandwiringwillfetchandexecutethoseinstructions.Hereistheentirecontrolsection:
Yes,thislooksprettycomplicated,butwehavelookedateverypartofitalready.TheonlythingwehadtoaddweresomeORgatesbecausemostofthe'enables'and'sets'needmultipleconnections.ThisactuallyhasalotfewerpartsthantheRAM,butthatwasmuchmorerepetitive.Mostofthemesshereisjustgettingthewiresfromoneplacetoanother.
ThebytethatisplacedintheInstructionRegistercausesacertainactivitytooccur.Eachpossiblepatterncausesadifferentactivity.Therefore,wehaveacodewhereeachofthe256possiblecodesrepresentsadifferentspecificactivity.
Asmentioned,thisiscalledtheInstructionCode.Anothernameforitis"machinelanguage,"becausethisistheonlylanguage(code)thatthemachine(computer)"understands."You"tell"themachinewhattodobygivingitalistofordersyouwantittocarryout.Butyouhavetospeaktheonlylanguagethatit"understands."Ifyoufeedittherightbyte-sizedpatternsofonsandoffs,youcanmakeitdosomethingthatwillbeuseful.
HerearealloftheInstructionCodesandourshorthandlanguagebroughttogetherinoneplace.
Believeitornot,everythingyouhaveeverseenacomputerdo,issimplytheresultofaCPUexecutingalongseriesofinstructionssuchastheonesabove.
AFEWMOREWORDSONARITHMETIC
Wedon'twanttospendalotoftimeonthissubject,buttheonlythingthatwehaveseensofarthatlookslikearithmeticistheadder,sowewilllookatsimpleexamplesofslightlymorecomplexarithmetic.Nottoteachyouhowtoactlikeacomputer,butjusttoprovetoyouthatitworks.
Hereishowyoudosubtraction.ItisdonewiththeadderandtheNOTgates.IfyouwanttosubtractR1fromR0,firstyouNOTR1backintoitself.Thenyouadd1toR1,thenyouAddR0toR1.
Thisshowsanexampleofsubtracting21from37:
Thelaststepisadding37+235,theanswerofwhichshouldbe272.Butasingleregistercannotholdanumberlargerthan255.ThereforetheadderturnsonitsCarrybit,andtheeightbitsremainingoftheanswerare00010000,whichis16,thecorrectanswerfor37minus21.
WhydoesNOTtingandADDingresultinsubtraction?Whydoyouhavetoadd
1afterNOTting?Whydoyouignorethecarrybit?Wearenotgoingtoattempttoansweranyofthesequestionsinthisbook.Thesearethedetailsthatkeepaveryfewengineersfromgettingagoodnight'ssleep.Thesebravepeoplestudytheseproblemsanddesignwaysforordinarypeopletonothavetounderstandit.
Hereishowyoudomultiplication.Whenwedomultiplicationwithapencilandpaperinthedecimalsystem,youhavetorememberyourmultiplicationtables,youknow,3times8equals24,6times9equals54,etc.
Inbinary,multiplicationisactuallymucheasierthanindecimal.1times1equals1,andforeveryothercombination,theansweriso!Itjustcouldn'tgetmuchsimplerthanthat!Here'sanexampleofmultiplying5times5withpencilandpaperinbinary.
Ifyoulookatwhat'shappeninghere,iftherightdigitofthebottomnumberisa1,youputthetopnumberintheanswer.Then,foreverydigittotheleftofthat,shiftthetopnumberleft,andifthebottomdigitisa1,addtheshiftedtopnumbertotheanswer.Whenyougetthroughtheeightbitsofthebottomnumber,you'redone.
Somultiplicationisaccomplishedwiththeadderandtheshifters.It'sassimpleasthat.Youcanwriteasimpleprogramlikethis:
R0containsthebottomnumber,R1containsthetopnumberandR2willcontaintheanswer.R3isusedtojumpoutoftheloopaftergoingthroughiteighttimes.
SeewhathappenswiththeRegistersasthisprogramgoesthroughitsloopthefirstthreetimes.
TheimportantthingthathashappenedhereisthatR1hasbeenaddedtoR2
twice.Ithappenedonthefirsttimethrough,whenR1contained00000101,andonthethirdtimethrough,afterR1hadbeenshiftedlefttwiceandthereforecontained00010100.R2nowcontains00011001binary,whichis16+8+1,or25decimal,whichisthecorrectanswerfor5times5.Theloopwillrepeat5moretimesuntilthebitinR3getsshiftedouttotheCarryFlag,butthetotalwon'tincreasebecausetherearenomoreisinR0.
Thisprogramwillgothrougheighttimes.Westartwith00000001inR3.Neartheendoftheprogram,R3getsshiftedleft.
Thefirstseventimesthrough,therewillbenocarry,sotheprogramwillgettothe'JMP53'andgobackuptothethirdinstructionoftheprogram.TheeighthtimeR3getsshiftedleft,theonebitthatisongetsshiftedoutofR3andintotheCarryflag.Therefore,the'JC68'willjumpoverthe'JMP53'andcarryonwithwhateverinstructionscomeafterthis.
ThebyteinR0getsshiftedrighttotestwhichbitsareon.ThebyteinR1getsshiftedlefttomultiplyitbytwo.WhentherewasabitinR0,youaddR1toR2.Andthat'sallthereistoit.
Onethingwedonotaddressinthisexampleiswhathappensiftheanswerofthemultiplicationismorethan255.Ifamultiplicationprogrammultipliestwoone-bytenumbers,itoughttobeabletohandleatwo-byteanswer.Thatwouldtakecareofanytwonumbersthatyoumightstartwith.ThiswouldbeaccomplishedwiththecarryflagandsomemoreJumpIfinstructions.Wewon'ttorturethereaderwiththedetails.
Readingaprogramliketheoneaboveisanentirelydifferentskillthanreadingthediagramsandgraphswehaveseensofarinthebook.Ihopeyouwereabletofollowit,butnooneisexpectedtobecomeanexpertatreadingprogramsbecauseofthisbook.
Divisionalsocanbedonebyourcomputer.Thereareseveralwaysitcanbedone,andwearenotgoingtoexamineanyoftheminanydetail.Justimaginethefollowingsimplemethod.Letssayyouwanttodividefifteenbythree.Ifyourepeatedlysubtractthreefromfifteen,andcountthenumberofsubtractionsyoucanaccomplishbeforethefifteenisallgone,thatcountwillbetheanswer.Likethesefivesteps:(1)15-3=12,(2)12-3=9,(3)9-3=6,(4)6-3-3,(5)3-3=0.Thisiseasilyturnedintoaprogram.
Computersalsohavewaysofhandlingnegativenumbersandnumberswithdecimalpoints.Thedetailsareverytedious,andstudyingthemwouldnot
enhanceourunderstandingofhowcomputerswork.ItstillcomesdowntonothingmorethanNANDgates.Oursimplecomputercoulddoallofthesethingswithprograms.
THEOUTSIDEWORLD
Whatwehavedescribedsofaristhewholecomputer.Ithastwoparts,theRAMandtheCPU.That'sallthereis.Thesesimpleoperationsarethemostcomplicatedthingsthatacomputercando.Theabilitytoexecuteinstructions,modifybyteswiththeALU,theabilitytojumpfromonepartoftheprogramtoanother,andmostimportantly,theabilitytojumpornotjumpbasedontheresultofacalculation.Thisiswhatacomputerisabletodo.Thesearesimplethings,butsinceitoperatessoquickly,itcandohugenumbersoftheseoperationsthatcanresultinsomethingthatlooksimpressive.
Thesetwopartsmakeitacomputer,butifallthecomputercoulddoisrunaprogramandrearrangebytesinRAM,noonewouldeverknowwhatitwasdoing.Sothereisonemorethingthatthecomputerneedsinordertobeuseful,andthatisawaytocommunicatewiththeoutsideworld.
Dealingwithanythingoutsideofthecomputeriscalled'Input/Output'or'I/O'forshort.Outputmeansdatagoingoutofthecomputer;Inputmeansdatacomingintothecomputer.Somethingsareinputonly,suchasakeyboard,somethingsareoutputonly,likeadisplayscreen,somethingsdobothinputandoutput,likeadisk.
AllweneedforI/Oisafewwires,andanewinstruction.
Forthewires,allwearegoingtodoistoextendtheCPUbusoutsideofthecomputerandaddfourmorewirestogowithit.Thiscombinationof12wireswillbecalledtheI/OBus.EverythingthatisconnectedtothecomputerisattachedtothisoneI/Obus.
ThedevicesthatareconnectedtotheI/Obusarecalled'peripherals,'becausetheyarenotinsidethecomputer,theyareoutsideofthecomputer,onitsperiphery(theareaaroundit.)
MorethanonethingcanbeattachedtotheI/Obus,butthecomputercontrolstheprocess,andonlyoneofthesethingsisactiveatatime.
EachthingattachedtotheI/ObushastohaveitsownuniqueI/Oaddress.ThisisnotthesameastheaddressesofthebytesinRAM,itisjustsome‘number’thattheperipheralwillrecognizewhenplacedonthebus.
HereiswhattheI/ObuslookslikeintheCPU,thereatthebottomrightofthedrawing.
InthediagrambelowarethewiresoftheI/OBus.TheCPUBusisthesameeight-wirebundlethatgoeseverywhereelse.The‘Input/Output’wiredetermineswhichdirectiondatawillbemovingontheCPUbus,eitherinorout.The‘Data/Address’wiretellsuswhetherwewillbetransferringabyteofdata,oranI/OAddressthatselectsoneofthemanydevicesthatcouldbeattachedtotheI/Obus.‘I/OClke’and‘I/OClks’areusedtoenableandsetregisterssothatbytescanbemovedbackandforth.
HereisthecontrolsectionwiringforthenewinstructionthatcontrolstheI/Obus.ThisshowswherethefournewwiresfortheI/Obuscomefrom.Theyareatthebottomrightofthedrawing.Theywerealsoshownonthefullcontrolsectiondiagramafewchaptersback.Sorryifthatwasconfusing,buthavingthatdiagraminthebookoncewasenough.
IRbits4and5areplacedontheI/Obusatalltimes.TomaketheI/Ooperationhappen,onlyonestepisneeded.ForOutput,RegBisenabled,andI/OClksisturnedonandoffduringstep4.Steps5and6donothing.ForInput,I/OClkeisenabled,andRegBissetduringstep5.Steps4and6donothing.
HereistheInstructionCodefortheI/Oinstruction:
ThisoneinstructioncanbeusedinfourdifferentwaysdependingonIRbits4and5,andthereforetherearefournewwordsforourlanguage.
EachI/Odevicehasitsownuniquecharacteristics,andthereforeneedsuniquepartsandwiringtoconnectittotheI/Obus.Thecollectionofpartsthatconnectsthedevicetothebusiscalleda"deviceadapter."Eachtypeofadapterhasaspecificnamesuchasthe'keyboardadapter'orthe'diskadapter.'
Theadapterdoesnothingunlessitsaddressappearsonthebus.Whenitdoes,thentheadapterwillrespondtothecommandsthatthecomputersendstoit.
Withan'OUTAddr'instruction,thecomputerturnsontheaddresswire,andputstheaddressofthedeviceitwantstotalkto,ontheCPUbus.Theperipheralrecognizesitsaddressandcomestolife.Everyotherperipheralhassomeotheraddress,sotheywon'trespond.
WearenotgoingtodescribeeverygateintheI/Osystem.Bythistime,youshouldbelievethatbytesofinformationcanbetransferredoverabuswithafewcontrolwires.ThemessageofthischapterisonlythesimplicityoftheI/O
system.TheCPUandtheRAMarethecomputer.Everythingelse,disks,printers,keyboards,themouse,thedisplayscreen,thethingsthatmakesound,thethingsthatconnecttotheinternet,allthesethingsareperipherals,andalltheyarecapableofdoingisacceptingbytesofdatafromthecomputerorsendingbytesofdatatothecomputer.Theadaptersfordifferentdeviceshavedifferentcapabilities,differentnumbersofregisters,anddifferentrequirementsasfaraswhattheprogramrunningintheCPUmustdotooperatethedeviceproperly.Buttheydon'tdoanythingfancierthanthat.ThecomputercontrolstheprocesswithaveryfewsimpleI/OcommandsthatareexecutedbytheCPU.
THEKEYBOARD
AkeyboardisoneofthesimplestperipheralsconnectedtotheI/Obus.Itisaninputonlydevice,andjustpresentsonebyteatatimetotheCPU.
Thekeyboardhaseightwiresinside,itsownlittlebusasshownontheright.Whenyoupressakey,itsimplyconnectselectricitytothewiresnecessarytocreatetheASCIIcodecorrespondingtothekeythatwaspressed.Thatlittleboxthatsays‘Control,’isalsonotifiedwhenakeyispressed,andsetstheASCIIcodeintotheKeycodeRegister.
Afterpressingakey,therewillbeanASCIIcodewaitingintheKeycodeRegister.Here’showtheCPUgetsthatcodeintooneofitsregisters.
ANDgate#1haseightinputs.TheyareconnectedtotheCPUbus,fourofthemthroughNOTgates.ThusthisANDgatewillturnonanytimethebuscontains00001111.ThisistheI/Oaddressofthiskeyboardadapter.
ANDgate#2comesononlyduring‘clks’timeofanOUTAddrinstruction.Itoperatesthe‘set’inputofaMemorybit.Ifthebuscontains00001111atthistime,the‘i’inputwillbeon,andtheMemorybitwillturnon.WhenthisMemorybitison,itmeansthatthekeyboardadapterisactive.
ANDgate#3comesonduring'elke'timeofanINDatainstruction.IftheMemorybitison,ANDgate#4willcomeonandtheKeycodeRegisterwillbeenabledontothebus,whichwillbesetintoRegBintheCPU.
EveryadapterthatisconnectedtotheI/Obusneedstohavethetypeofcircuitryweseeingates#1and#2andthememorybitabove.Eachadapterwillhaveadifferentcombinationthatturnsgate#1on;thisiswhatallowstheCPUtoselecteachadapterindividually.
HereisalittleprogramthatmovesthecurrentkeypressintoReg3intheCPU.
Thatlittle'Control'boxclearstheKeycodeRegisterafterithasbeensenttotheCPU.
TheprogramrunningintheCPUwillcheckthekeyboardadapteronaregularbasis,andifthebytethatitreceivesisallzeros,thennokeyhasbeenpressed.Ifthebytehasoneormorebitson,thentheprogramwilldowhatevertheprogramhasbeendesignedtodowithakeystrokeatthattime.
Again,wearenotgoingtogothrougheverygateintheKeyboardadapter.Alldeviceadaptershavethesamesortsofcircuitryinordertobeabletorespondwhentheyareaddressed,andsendorreceivebytesofinformationasneeded.Butitisnomorecomplicatedthanthat.ThatisallthatI/Odevicesandadaptersdo.
THEDISPLAYSCREEN
Televisionandcomputerdisplayscreensworkthesameway,themaindifferencebetweenthemisonlywhattheydisplay.Thisisnotactuallycomputertechnology,becauseyoudon'tneedadisplayscreentohaveacomputer,butmostcomputersdohaveascreen,andthecomputerspendsalotofitstimemakingthescreenlooklikesomething,soweneedtoknowalittlebitabouthowitworks.
Televisionappearstogiveyoumovingpictureswithsound.Thepicturesandsoundaredoneseparately,andinthischapter,weareonlyconcernedwithhowthepictureworks.
Thefirstthingtoknowisthatalthoughthepictureappearstobemoving,itisactuallyaseriesofstillpicturespresentedsoquicklythattheeyedoesn'tnoticeit.Youprobablyalreadyknewthat,buthere'sthenextthing.Youhaveseenmotionpicturefilm.Itisaseriesofpictures.Towatchamovie,youputthefilminaprojector,whichshineslightthroughonepicture,thenmovesthefilmtothenextpicture,shineslightthroughit,etc.Itusuallyrunsat24picturespersecond,whichisfastenoughtogivetheillusionofaconstantlymovingpicture.
Televisiongoesabitfaster,about30picturespersecond,butthereisanother,muchbiggerdifferencebetweenfilmandtelevision.Withthemoviefilm,eachstillpictureisshownallatonce.Eachpictureiscomplete,whenyoushinethelightthroughit,everypartofthepictureappearsonthescreensimultaneously.Televisionisnotcapableofdoingthis.Itdoesnothaveawholepicturetoputonthescreenallatonce.
Allthatatelevisioncandoatoneinstantintime,istolightuponesingledotonthescreen.Itlightsuponedot,thenanotherdot,thenanother,veryquicklyuntilonewholepicture'sworthofdotshasbeenlit.Thiswholescreen'sworthofdotsmakesuponestillpicture,thusithastolightupallofthedotswithinonethirtiethofasecond,andthendoitalloveragainwiththenextpicture,etc.untilithasplaced30picture'sworthofdotsonthescreeninonesecond.SotheTVisverybusylightingupindividualdots,30timesthenumberofdotsonthescreen,everysecond.
Usually,thetopleftdotislitfirst,thentheonetoitsright,andsoonacrossthetopofthescreentothetoprightcorner.Thenitstartswiththesecondlineofdots,goingacrossthescreenagain,thethirdline,etc.untilithasscannedtheentirescreen.Thebrightnessofeachdotishighorlowsothateachpartonthe
screengetslituptotheproperbrightnesstomakethescreenlookliketheintendedimage.
Atanyoneinstantintime,thetelevisionisonlydealingwithonesinglesolitarydotonthescreen.Sowithtelevision,therearetwoillusions-theillusionofmotioncomingfromaseriesofstillpictures,aswellastheillusionofcompletestillpicturesthatareactuallydrawnonedotatatime.Thissecondillusionisaidedbywhatthescreeninmadeof,eachdotonlygetslitupforatinyfractionofasecond,anditstartstofadeawayimmediately.Fortunately,whateverthescreenismadeofthatglows,continuestoglowtosomedegreebetweenonetimewhenthedotislitupand1/30thofasecondlaterwhenthatsamedotgetslitupagain.
Totheeye,youjustseeamovingpicture,buttherearealotofthingsgoingontomakeitappearthatway.
Inacomputer,asingledotonthescreeniscalleda'pictureelement,'or'pixel'forshort.
Computerscreensworkjustliketelevisions.Theyalsohavetoscantheentirescreen30timesasecondtolightupeachindividualpixelandtherebymakeanimageappear.Evenifthecontentofthescreenisnotchanging,somethinginthecomputerhastoscanthatunchangingimageontothescreen30timeseverysecond.Noscanning,nopicture-that'sjustthewayitworks.
We'renotgoingtogointothesameamountofdetailherethatwedidwiththeCPUandtheRAM,thosetwoarewhatmakeitacomputer,butifwewanttoknowhowourcomputerisabletoputsomethingonthescreenthatwecanread,weneedtohavethebasicideaofhowitworks.
Inthischapterwewilllookatthesimplestkindofscreen,thekindthatisblackandwhite,andwhosepixelscanonlyeitherbefullyonorfullyoff.Thistypeofscreencandisplaycharactersandthetypeofpicturesthataremadeoflinedrawings.Laterinthebookwewillseethefewsimplechangesthatenableascreentodisplaythingslikecolorphotographs.
Themajorpartsarethree.Firstthereisthecomputer,wehaveseenhowthatworks.IthasanI/OBusthatcanmovebytestoandfromthingsoutsideofthecomputer.Secondisthescreen.Thescreenisjustalargegridofpixels,eachofwhichcanbeselected,oneatatime,andwhileselected,caneitherbeturnedon,ornot.Thethirditemisthe'displayadapter.'ThedisplayadapterisconnectedtotheI/OBusononeside,andtothescreenontheotherside.
TheheartofadisplayadapterissomeRAM.ThedisplayadapterneedsitsownRAMsoitcan"remember"whichpixelsshouldbeon,andwhichpixelsshouldbeoff.Inthetypeofscreenwearegoingtodescribehere,thereneedstobeonebitinRAMforeachpixelonthescreen.
Inordertomakethescreenscaneverypixel30timeseverysecond,theDisplayAdapterneedsitsownclockthatticksataspeedthatis30timesthenumberofpixelsonthescreen.Ateachtickoftheclock,onepixelisselectedanditisturnedonornotbythecorrespondingbitfromtheRAM.
Asanexample,letsuseanoldtypeofscreen.Itisablackandwhitescreenthatdisplays320pixelsacrossthescreenand200pixelsdown.Thatcomesoutto64,000individualpixelsonthescreen.Eachpixelonthescreenhasauniqueaddressconsistingoftwonumbers,thefirstbeingtheleft-rightorhorizontalposition,andtheotherbeingtheup-downorverticalposition.Theaddressofthetopleftpixelis0,0andthebottomrightpixelis319,199
64,000pixelstimes30picturespersecondmeansthatthisDisplayAdapter'sclockneedstotick1,920,000timespersecond.Andsincethereareeightbitsinabyte,wewillneed8,000bytesofdisplayRAMtotelleachofthe64,000screenpixelswhethertobeonoroff.
Thedisplayadapterhasaregisterthatsetsthehorizontalpositionofthecurrentpixel.Thedisplayadapteradds1tothisregisterateverytickoftheclock.Itstartsatzero,andwhenthenumberinitgetsto319,thenextstepresetsitbacktozero.Soitgoesfromzeroto319overandoveragain.Thereisalsoaregisterthatsetstheverticalpositionofthecurrentpixel.Everytimethehorizontalregistergetsresettozero,thedisplayadapteradds1totheverticalregister.Whentheverticalregisterreaches199,thenextstepwillresetittozero.Soasthehorizontalregistergoesfromzeroto319200times,theverticalregistergoesfromzeroto199once.
Thecurrentlyselectedscreenpixeliscontrolledbytheseregisters,soasthehorizontalregistergoesfromoto319,thecurrentpixelgoesacrossthescreenonce.Thentheverticalregisterhasoneaddedtoit,andthecurrentpixelmovesdowntothefirstpixelonthenextline.
Thus,theclockandthehorizontalandverticalregistersselecteachpixelonthescreen,oneatatime,goinglefttorightinonerow,thenselectingeachpixelinthenextrowdown,thenthenext,etc.untileverypixelonthescreenhasbeenselectedonetime.Thenitstartsalloveragain.
Atthesametime,thereisanotherregisterthatcontainsadisplayRAMaddress.
Thisregisteralsogetssteppedthrough,althoughweonlyneedonenewbyteforeveryeightpixels.Thebitsofeachbyte,oneatatime,aresenttothescreenateightconsecutivepixelstoturnthemonoroff.Aftereveryeightpixels,theRAMaddressregisterhas1addedtoit.Bythetimeallofthepixelshavebeensteppedthrough,theentireRAMhasalsobeensteppedthrough,andoneentirepicturehasbeendrawn.Whenthehorizontalandverticalregistershavebothreachedtheirmaximums,andareresettozero,theRAMaddressisalsoresettozero.
Thedisplayadapterspendsmostofitstimepaintingthescreen.TheonlyotherthingithastodoistoacceptcommandsfromtheI/OBusthatwillchangethecontentsofthedisplayadapterRAM.WhentheprogramrunningintheCPUneedstochangewhat'sonthescreen,itwillusetheI/OOUTcommandtoselectthedisplayadapter,andthensendadisplayadapterRAMaddressandthenabyteofdatatostoreatthataddress.Thenastheadaptercontinuestorepaintthescreen,thenewdatawillappearonthescreenattheappropriatespot.
ThedisplayadapterRAMisbuiltdifferentlythantheRAMinourcomputer.Itkeepstheinputandoutputfunctionsseparate.Theinputsofallstoragelocationsareconnectedtotheinputbus,andtheoutputsofallstoragelocationsareconnectedtotheoutputbus,buttheinputbusandtheoutputbusarekeptseparate.Thentherearetwoseparatememoryaddressregisters,oneforinputandoneforoutput.TheinputMARhasagridthatonlyselectswhichbytewillbe'set,'andtheoutputMARhasaseparategridthatonlyselectswhichbytewillbe'enabled.'
Withthissetup,thescreenandthedisplayRAMcanbothbecontinuouslyscannedusingonlytheoutputMARandtheenablebit.WhentheI/OBusisusedtowriteintothedisplayRAM,itusesonlytheinputMARandthesetbit.
Thisishowthedisplayadaptercreatesanimageonthescreen.Becauseofthewayitworks,thereisaninterestingrelationshipbetweenwhichbitsinthedisplayRAMcorrespondtowhichpixelsonthescreen.Asitscansthefirsteightpixelsofthetopline,itusestheindividualbitsofbyteoofitsRAMtoturnthepixelsonoroff.Asitscansthesecondeightpixels,itusestheindividualbitsofbyte1ofitsRAM,etc.Ittakes40bytesofRAMtodrawthefirstline,andsothelasteightpixels,whicharenumbered312through319,comefromRAMbyte39.Thesecondrowusesbyte40todrawitsfirst8pixels,etc.
Ifyouwanttowritelettersandnumbersonthescreen,howdoyoudoit?IfyouputtheASCIIcodefor'A'intoabyteinthedisplayRAM,youwilljustgeteightpixelsinarowwhereoneisoff,thenoneison,thenfiveareoffandthelastoneison.That'snotwhatan'A'shouldlooklike.
Thereisasolutionforthis,anditinvolves...
ANOTHERCODE
Whenyouwanttoprintordisplaywrittenlanguage,youneedtotranslatetheASCIIcodeintosomethingthatisreadablebyaliveperson.Wehaveacode,01000101,thatappearsontheASCIIcodetablenexttotheletter'E.'Buthowdoesthecomputerturn01000101intoareadable'E'?
Wehaveadisplayscreen,butthescreenisajustagridofpixels,therearenohumanreadable'E'sinanythingwehavedescribedsofar.Inordertogetan'E'onthescreen,therehastobesomethingthatmakesthatshapethatwerecognizeasaletterofthealphabet.
Therefore,weneedanothercode.Thiscodeisreallyaboutlittlepicturesmadeoutofdots.Foreachcharacterthatwewanttobeabletodrawonthescreen,weneedalittlepictureofthatcharacter.Ifyoutakeagrid8pixelswideand8pixelshigh,youcoulddecidewhichpixelshadtobeontomakealittlepicturethatlookslikethecharacterthatyouwanttodrawonthescreen,likethis:
Ifyouturnthispictureintoonsandoffs,youcouldstoreitineightbytes.Ifthereare100differentcharactersthatyouwanttobeabletodisplayonthescreen,thenyou'dneed100differentlittlepictureslikethis,anditwouldrequire800bytesofRAMtostoreit.Ourlittlecomputeronlyhasa256byteRAM,sothiswouldbeagoodtimetoimaginethatlargerversionthatwedescribedearlier.
These800bytesareatypeofcodeknownasa"font."
Ifyouwanttomakeacharacterappearinacertainplaceonthescreen,youneedtochoosethecorrectlittlepicturefromthefont,andthenuseI/Oinstructionstocopytheeightbytesofthepicturetotheproperbytesinthedisplayadapter'sRAM.
IfthepicturesinourfontarearrangedinthesameorderastheASCIIcodetable,thenwecanusethenumericvalueofanASCIIcodetofindthecorrespondingpicturewithinthefont.TheASCIIcodefor'E'is01000101.Ifyouapplythebinarynumbercodetothesamepatternofonesandzeros,yougetthedecimalnumber69.'E'then,isthe69thcodeinASCII,andthepictureofan'E'willbethe69thpicturewithinthefont.Sincethereareeightbytesineachpicture,youmultiplythe69by8,andthattellsyouthatthepicturefor'E'willbetheeightbytesstartingataddress552.
NowweneedtoknowwheretocopythesebytestointhedisplayRAM.Letssaythatwewanttodisplayan'E'attheverytopleftofthescreen.Wherearethebitsthatturnonthepixelsthatweareinterestedin?Well,thefirstlineiseasy,itisthefirsteightbitsofthedisplayRAM,Addresso.SoweuseaseriesofOUTinstructionstocopyRAMaddress552todisplayRAMaddresso.Now,whereisthesecondlineinthedisplayRAM?Thedisplaypaintsall320bitsofthetoprowbeforeitmovesdowntothesecondrow.Thatmeansthatituses40bytesoneachrow,sothetoprowusesbytes0-39.Thatmeansthatthesecondbyteofthepictureof'E'atRAMaddress553needstobewrittenataddress40inthedisplayRAM.Similarly,thethirdthrougheighthbytesgetwrittenatbytes80,120,160,200,240and280.Whenyouhavedoneallofthat,youwouldthenseeacomplete'E'onthescreen.Ifyouwantedtowritean'X'onthescreenrightnexttothe'E',youwouldlocatetheeightbytesinthefontfor'X'andcopythemintodisplayRAMbytes1,41,81,121,161,201,241and281.Ifyouneed27'E'sonyourscreen,youjustcopytheone'E'inyourfontto27differentplacesinthedisplayRAM.
Ofcourse,thisseemslikealotofworkjusttomakeasingleletterappearonthescreen.Theprogramthatdoesthiswouldneedaloopofinstructionsthatcalculatesthefirst'from'and'to'addresses,thenissuestheappropriateOUT
instructionstocopythefirstbytetothedisplayRAM.Thentheloopwouldrepeat,updatingbothaddresseseachtime,untilalleightbyteshadbeencopiedtotheappropriateplaces.We'renotgoingtowritethisprogram,butitcouldeasilybea50instructionprogramthathastolooparoundeighttimesbeforeit'sfinished.Thatmeansthatitcouldtake400instructioncyclesjusttoputonecharacteronthescreen!Ifyoudrew1000charactersonthescreen,thatmighttake400,000instructioncycles.Ontheotherhand,that'sstillonlyaboutonequarterofonepercentofwhatthiscomputercandoinonesecond.
Thisjustgoestoshowyouwhycomputersneedtobesofast.Theindividualthingsthattheydoaresosmall,thatittakesahugenumberofstepstogetanythingdoneatall.
THEFINALWORDONCODES
Wehaveseenseveralcodesusedinourcomputer.Eachonewasdesignedforaspecificpurpose.Individualcodedmessagesareputinbytes,andmovedaroundandusedtogetthingsdone.
Thebytesdonot'know'whichcodewasusedtochoosethepatternthattheycontain.Thereisnothinginthebyteitselfthattellsyouwhichcodeitissupposedtobe.
Certainpartsofthecomputerarebuiltwithvariouscodesinmind.IntheALU,theadderandcomparatorarebuilttotreatbytesasthoughtheycontainvaluesencodedwiththebinarynumbercode.SoaretheMemoryAddressRegisterandtheInstructionAddressRegister.
TheInstructionRegisterisbuilttotreatitscontentsasthoughitcontainsvaluesencodedwiththeInstructionCode.
TheDisplayadapterRAMbitsarejustonsoroffsforindividualpixels.Picturesandfontsarestringsofbytesthatwillresultinsomethingthatcanberecognizedbyapersonwhenitisorganized,andthebrightnessesareset,bythewiringofadisplayadapterandscreen.
TheASCIIcodetabledoesnotappearanywhereinsidethecomputerbecausethereisnowaytorepresentaletterofthealphabetexceptbyusingacode.
TheonlyplaceswhereASCIIgetsconvertedbetweencharactersandthecodeforthecharacter,areintheperipherals.Whenyoupress'E'onthekeyboard,yougettheASCIIcodeforan'E.'WhenyousendtheASCIIcodeforan'E'toaprinter,itprintstheletter'E.'ThepeoplewhobuildtheseperipheralshaveanASCIIcodetableinfrontofthem,andwhentheybuildakeyboard,theswitchunderthefourthbuttoninthesecondrow,whichhastheletter'E'printedonit,iswireduptotheproperbuswirestoproducethecodethatappearsnexttotheletter'E'ontheASCIIcodetable.
An'E'isthefifthletterofanalphabetusedbypeopletorepresentsoundsandwordsintheprocessofwritingdowntheirspokenlanguage.Theonly'E'sinthecomputeraretheoneonthekeyboardandtheonesthatappearonthescreen.Allthe'E'sthatareinbytesarejustthecodethatappearsnexttothe'E'onanASCIIcodetable.Theyarenot'E's,thereisnowaytoputan'E'inacomputer.Evenifyouputapictureofan'E'inacomputer,itisn'tactuallyan'E'untilitisdisplayedonthescreen.That'swhenapersoncanlookatitandsay"That'san
E."
Bytesaredumb.Theyjustcontainpatternsofonsandoffs.Ifabytecontains01000101,andyousendittotheprinter,itwillprinttheletter'E.'IfyousendittotheInstructionRegister,thecomputerwillexecuteaJumpinstruction.IfyousendittotheMemoryAddressRegister,itwillselectbytenumber69oftheRAM.IfyousendittoonesideoftheAdder,itwilladd69towhateverisontheothersideoftheAdder.Ifyousendittothedisplayscreen,itwillsetthreepixelsonandfivepixelsoff.
Eachofthesepiecesofthecomputerisdesignedwithacodeinmind,butonceitisbuilt,themindisgoneandeventhecodeisgone.Itjustdoeswhatitwasdesignedtodo.
Thereisnolimittothecodesthatcanbeinventedandusedinacomputer.Programmersinventnewcodesallthetime.Likethecashregisterinthefastfoodrestaurantmentionedearlier,somewhereinthatmachineisabitthatmeans'includeFrenchfries.'
THEDISK
Mostcomputershaveadisk.ThisissimplyanotherperipheralthatisattachedtotheI/Obus.Thedisk'smissionisverysimple;itcandotwothings.Youcansenditbytes,whichitwillstore,oryoucantellittosendbacksomebytes,whichwerestoredpreviously.
Therearetworeasonsthatmostcomputershaveadisk.First,theyhavetheabilitytostoreahugenumberofbytes,manytimesgreaterthantheComputer'sRAM.TheCPUcanonlyexecuteprogramsthatareinRAM,itcanonlymanipulatebytesthatareinRAM.ButthereisneverenoughRAMtostoreallofthethingsthatyoumaywanttodowithyourcomputer.Andsoadiskwillholdeverything,andwhenyouwanttodoonething,thebytesonthediskforthatonethingwillbecopiedintoRAMandused.Thenwhenyouwanttodosomethingdifferent,thebytesforthenewactivitywillbecopiedfromthediskintothesameareaofRAMthathadbeenusedforthefirstactivity.
Thesecondreasonthatcomputershavedisks,isthatthebytesstoredonthediskdonotdisappearwhenyouturnthepoweroff.TheRAMlosesitssettingswhenyouturnthecomputeroff,whenyouturnitbackon,allbytesare00000000,butthediskretainseverythingthathasbeenwrittenonit.
Acomputerbithasbeendefinedsofarasaplacewherethereisorisnotsomeelectricity.Butpriortothat,wedefineditasaplacethatcanbeinoneoftwodifferentstates.Onadisk,theelectricbitsaretransformedintoplacesonthesurfaceofthediskthathavebeenmagnetizedonewayortheother.Sincemagnetshavenorthandsouthpoles,thespotonthediskcanbemagnetizedeithernorth-southorsouth-north.Onedirectionwouldrepresentazero,andtheotherdirection,aone.Onceaspotismagnetized,itstaysthatwayunlessthesamespotgetsmagnetizedtheotherway.Turningthepoweroffhasnoeffectonthemagnetizedspots.
Adisk,asitsnameimplies,isaroundthing,thatspinsaroundquickly.Itiscoatedwithamaterialthatcanbemagnetizedeasily.Doyourememberthetelegraph?Atthereceivingend,thereisapieceofmetalwithawirewrappedaroundit.Thatpieceofmetalturnsintoamagnetwhenelectricitymovesthroughthewire.Thediskhasatinyversionofthiscalleda‘head’mountedonanarm.Thearmholdstheheadveryclosetothesurfaceofthespinningdisk,andthearmcanswingbackandforth,sothattheheadcanreachanypointonthesurfaceofthedisk.Ifyouputelectricitythroughthehead,itcanmagnetize
thesurfaceofthedisk.Also,itworkstheotherwayaround;whentheheadpassesoveramagnetizedarea,itmakeselectricityappearinthewireswrappedaroundthehead.Thus,theheadcaneitherwriteonthediskorreadwhathasbeenpreviouslywrittenonthedisk.Thebitsofthebytesarewrittenoneafteranotheronthedisksurface.
Thesurfaceofthediskisdividedintoaseriesofrings,calledtracks,veryclosetoeachother.Theheadcanmoveacrossthesurfaceandstoponanyoneofthetracks.Eachcirculartrackisusuallydividedintoshortpiecescalledsectors.Sinceadiskhastwosides,usuallybothsidesarecoatedwiththemagneticmaterialandthereisaheadoneachside.
InRAM,everybytehasitsownaddress.Onadisk,thereisalsoawaytolocatebytes,butitisverydifferent.Youhavetospecifywhichhead,whichtrackandwhichsectoratwhichablockofbytesislocated.Thatisthetypeof“address”thatthedataonadiskhas,like“Head0,Track57,Sector15.”Andatthataddress,thereisnotjustonebyte,butablockofbytes,typicallyseveralthousand.Fortheexamplesinourbook,sinceourRAMissosmall,wewilltalkaboutadiskthatstoresblocksof100bytes.
Whenadiskisreadorwritten,thereisnowaytoaccessanindividualbyteintheblockofbytes.ThewholeblockhastobetransferredtoRAM,workedoninRAM,andthenthewholeblockhastobewrittenbacktothedisk.
Thediskspinsquickly,fasterthanthatfanonyourdesk;manypopulardisks
spin7200timesaminute,whichis120timespersecond.That'sprettyfast,butcomparedtotheCPU,itisstillprettyslow.Inthetimethatthediskspinsaroundonetime,theClockwilltickovereightmilliontimes,andourCPUwillexecutewelloveramillioninstructions.
Thedisk,likeeveryperipheral,isconnectedtoitsownadapter,whichinturnisconnectedtotheI/Obus.Thediskadapterdoesafewthings.Itacceptscommandstoselectahead,selectatrackandselectasector.Itacceptscommandstoreadfromorwriteto,theblockofbytesatthecurrentlyselectedhead,trackandsector.TherewillalsoprobablybeacommandwheretheCPUcancheckthecurrentpositionofthearmandthedisk.
Thecommandtoselectaheadcanbecompletedimmediately,butwhenitgetsacommandtoselectatrack,ithastomovetheheadtothattrack,whichtakesalongtimeintermsofinstructioncycles.Whenitgetsacommandtoselectasector,ithastowaitforthatsectortospinaroundtowheretheheadis,whichalsotakesalongtimeintermsofinstructioncycles.WhentheCPUhasdeterminedthattheheadhasarrivedatthedesiredtrackandsector,thentheI/Ocommandsforreadingorwritingcanbeexecuted,andonebyteatatimewillbetransferredovertheI/Obus.Aprogramthatreadsorwritesablockofbyteshastocontinuetheprocessuntilthewholeblockofbytesiscomplete.WithoursimpleI/Osystem,theindividualbytesmovebetweenthediskandaCPUregister.TheprogramthatisrunninghastomovethesebytestoorfromRAM,usuallyinconsecutivelocations.
Thisisallthatadiskdoes.Youhaveprobablyusedacomputerthathadadisk,anddidn'tneedtoknowanythingaboutheads,tracksandsectors.Andthatisagoodthing,becauseitisprettyannoyingtohavetodealwithadiskatthatlevelofdetail.Wewilllookathowadiskisnormallyusedlaterinthebook.
Anotherlanguagenote:Thereareseveralwordsthatmeanvirtuallythesamething,butforsomereasoncertainwordsgowithcertaintechnologies.
Ifyouwanttosendsomeonealetter,firstyouwriteitonapieceofpaper,thenwhentherecipientgetstheletter,hereadsit.
Inthedaysoftaperecorders,youwouldstartwithablanktape.Thenyouwouldrecordsomemusiconthetape.Whenyouwantedtohearthemusicagainyouwouldplaythetape.
Whenitcomestocomputerdisks,puttingsomethingonthediskiscalledwriting.Gettingsomethingoffthediskiscalledreading.
PuttingsomethingintoRAMiscalledwritingorstoring.GettingsomethingoutofRAMiscalledreadingorretrieving.
PuttingsomethingintoaCPUregisterisusuallycalledloading.
Puttingmusiconadiskissometimescalledrecording,sometimesburning.Listeningtoadiskisstillusuallycalledplaying,butifyouarecopyingitontoyourcomputer,thenitiscalledripping.
Writing,recording,storing,loadingandburningallmeanprettymuchthesamething.Reading,retrieving,playingandrippingarealsoverysimilar.Theymeanthesamethings,it'sjustadifferenceofwords.
EXCUSEMEMA'AM
ThereisoneotherthingthatmostcomputershaveaspartoftheirInput/Outputsystem.Acomputerdoesn'tneedoneofthesetobecalledacomputer,sowewillnotgothrougheverygateneededtobuildit.Butitisaverycommonthing,sowewilldescribehowitworks.
YouknowifMomisinthekitchenstirringapotofsoup,andlittleJoeycomesrunninginandsays"Iwantaglassofmilk,"Momwillputdownthespoon,goovertothecabinet,getaglass,gototherefrigerator,pourthemilk,handittoJoey,andthenshewillgobacktothestove,pickupthespoonandresumestirringthesoup.Thesoupstirringwasinterruptedbygettingaglassofmilk,andthenthesoupstirringresumed.
Thisthingthatmostcomputershave,iscalledan"Interrupt,"anditworksverymuchlikewhathappenedwithMomandJoey.
AninterruptstartswithonemorewireaddedtotheI/OBus.ThiswireisusedbycertaindeviceadapterstolettheCPUknowthatit'sagoodtimefortheCPUtodoanI/Ooperation,likerightaftersomeonepressesakeyonthekeyboard.WhenadeviceadapterturnstheInterruptbiton,thenexttimethesteppergetsbacktostep1,thenextinstructioncyclewillnotdotheusualfetchandexecute,butratheritwilldoofthefollowing:
TheresultofthissequenceisthatthecurrentIARandFlagsaresavedtoRAMaddressesoand1,andtheyarereplacedwiththecontentsofRAMbytesaddresses2and3.ThentheCPUreturnstoitsnormalfetchandexecuteoperation.ButtheIARhasbeenreplaced!Sothenextinstructionwillbefetched
fromwhateveraddresswasinRAMbyte2.
Inotherwords,whattheCPUhadbeendoingissaved,andtheCPUissentofftodosomethingelse.Ifattheendofthisnewactivity,theprogramputsRAMbytesoandlbackintotheIARandFlags,theCPUwillpickupfromexactlywhereitleftoff,beforeitwasinterrupted.
ThissystemisveryusefulfordealingwithI/Ooperations.Withoutinterrupts,theprogramrunningintheCPUwouldhavetomakesuretocheckallofthedevicesontheI/OBusonaregularbasis.Withinterrupts,theprogramcanjustdowhateveritisdesignedtodo,andtheprogramthatdealswiththingslikekeyboardinputwillbecalledautomaticallyasneededbytheinterruptsystem.
WehavenotincludedthisinourCPUbecauseitwouldjustmakeourControlSectionwiringdiagramtoobig.Itwouldneedtoaddthefollowing:twomorestepstothestepper,wiringtodotheabove8stepsinplaceofthenormalinstructioncycle,pathsfortheFlagsregistertogettoandfromthebus,amethodofsendingabinaryo,1,2or3toMAR,andaninstructionthatrestoresRAMbytesoand1totheIARandFlagsregister.
AndthatisanInterruptsystem.Asfarasthelanguageisconcerned,thecomputerdesignerstookanexistingverb,'interrupt,'anduseditinthreeways:Itisaverbin"thekeyboardinterruptedtheprogram,"itisanadjectivein"ThisistheInterruptsystem,"anditisanounin"theCPUexecutedaninterrupt."
THAT'SALLFOLKS
Yes,thisistheendofourdescriptionofacomputer.Thisisallthereis.Everythingyouseeacomputerdoisalongconcatenationoftheseverysimpleoperations,theADDing,NOTting,Shifting,ANDing,ORing,XORingofbytes,Storing,Loading,JumpingandI/Ooperations,viatheexecutionoftheinstructioncodefromRAM.Thisiswhatmakesacomputeracomputer.Thisisthesumtotalofthesmartsinacomputer.Thisisallthethinkingthatacomputeriscapableof.Itisamachinethatdoesexactlywhatitisdesignedtodo,andnothingmore.Likeahammer,itisatooldevisedbymantodotasksdefinedbyman.Itdoesitstaskexactlyasdesigned.Alsolikeahammer,ifitisthrownindiscriminatelyitcandosomethingunpredictableanddestructive.
Thevarietyofthingsthecomputercanbemadedoislimitedonlybytheimaginationandclevernessofthepeoplewhocreatetheprogramsforthemtorun.Thepeoplewhobuildthecomputerskeepmakingthemfaster,smaller,cheaperandmorereliable.
Whenwethinkofacomputer,weprobablythinkofthatboxthatsitsonadeskandhasakeyboard,mouse,screenandprinterattachedtoit.Butcomputersareusedinmanyplaces.Thereisacomputerinyourcarthatcontrolstheengine.Thereisacomputerinyourcellphone.Thereisacomputerinmostcableorsatellitetelevisionboxes.ThethingsthattheyallhaveincommonarethattheyallhaveaCPUandRAM.Thedifferencesareallintheperipherals.Acellphonehasasmallkeyboardandscreen,amicrophoneandaspeaker,andatwo-wayradioforperipherals.Yourcarhasvarioussensorsandcontrolsontheengine,andthedialsofthedashboardforperipherals.Thecashregisterinafastfoodrestauranthasafunnykeyboard,asmalldisplayscreenandasmallprinterforreceipts.Therearecomputersinsometrafficlightsthatchangethelightsbasedonthetimeofdayandtheamountoftrafficthatcrossesthesensorsembeddedintheroadway.ButtheCPUandRAMmakeitacomputer,theperipheralscanbeverydifferent.
Fortherestofthebookwewilllookatmiscellaneoussubjectsrelatedtounderstandinghowcomputersareused,afewinterestingwordsthatarerelatedtocomputers,someoftheirfrailtiesandafewotherlooseends.
HARDWAREANDSOFTWARE
You'veheardofhardware.Thatwordhasbeenaroundforalongtime.Therehavebeenhardwarestoresforacenturyormore.Ithinkthatahardwarestoreoriginallysoldthingsthatwerehard,likepotsandpans,screwdrivers,shovels,hammers,nails,plows,etc.Perhaps'hardware'meantthingsthatweremadeoutofmetal.Today,somehardwarestoresnolongersellpotsandpans,buttheysellhugevarietyofhardthings,likeboltsandlawnmowers,alsolumberandalotofsoftthingstoo,likecarpet,wallpaper,paint,etc.Butthesesoftthingsarenotcalledsoftware.
Theword'software'wasinventedsomewhereintheearlydaysofthecomputerindustrytodifferentiatethecomputeritselffromthestateofthebitswithinit.Softwaremeansthewaythebitsaresetonoroffinacomputerasopposedtothecomputeritself.Rememberthatbitscanbeeitheronoroff.Thebithasalocationinspace,itismadeofsomething,itexistsinspace,itcanbeseen.Thebitishardware.Whetherthebitisonoroffisimportant,butit'snotaseparatepartthatyouboltintothecomputer,itisthethinginthecomputerthatischangeable,thethingthatcanbemolded,itis'soft'inthatitcanchange,butyoucan'tpickitupinyourhandallbyitself.Thisthingiscalledsoftware.
Thinkofablankvideotape.Thenrecordamovieonit.Whatisthedifferencebetweentheblankvideotapeandthesamevideotapewithamovieonit?Itlooksthesame,itweighsthesame,youcan'tseeanydifferenceonthesurfaceofthetape.Thatsurfaceiscoatedwithveryfineparticlesthatcanbemagnetized.Intheblanktape,theentiresurfaceofthetapeismagnetizedinrandomdirections.Afterrecordingthemovieonthetape,somelittleplacesonthetapearemagnetizedinonedirectionandotherlittleplacesaremagnetizedintheotherdirection.Nothingisaddedtoortakenawayfromthetape,it'sjustthewaythemagneticparticlesaremagnetized.WhenyouputthetapeintoaVCRitplaysamovie.Thetapeishardware,thepatternofthedirectionsofmagnetizationonthetapeissoftware.
Inacomputer,thereareagreatmanybits.Aswehaveseen,alotofbitshavetobesetincertainwaysinordertomakethecomputerdosomethinguseful.Thebitsinthecomputerarealwaysthere.Ifyouwantthecomputertodoacertainthing,yousetthosebitsonoroffaccordingtothepatternthatwillmakethecomputerdowhatyouwantittodo.Thispatterniscalledsoftware.Itisnotaphysicalthing,itisjustthepatterninwhichthebitsareset.
Sothedifferencebetweenhardwareandsoftwareisn'tlikemetalversusrubber.Bothmetalandrubberarehardwareasfarasthecomputerdefinitionisconcerned.Hardwareissomethingyoucanpickup,see,handle.Softwareisthewaythehardwareisset.Whenyoubuysoftware,itisrecordedonsomething,usuallysomekindofdisk.Thediskishardware,thespecificpatternrecordedonthatdiskissoftware.Anotherdiskmaylookjustlikeit,buthavecompletelydifferentsoftwarewrittenonit.
Anotherwaytoseethedifferencebetweenhardwareandsoftwareishoweasyitistosenditacrossadistance.IfyouhaveavasethatyouwanttosendtoyourauntMillieforherbirthday,youhavetopackthevaseinaboxandhaveatrucktakeitfromyourhousetoherhouse.Butifyouwanttogiveherthepresentofmusic,youmightgotothestore,buyheradiskandmailit,butyoumightalsobuyheragiftcertificateontheInternet,sendherane-mail,andhaveherdownloadthemusic.Inthatcase,themusicwillgettoherhousewithoutatruckhavingtogothere.ThemusicwillbetransportedsolelybythepatternofelectricitythatcomesovertheInternetconnectiontoherhouse.
Anotherwaytoseethedifferencebetweenhardwareandsoftwareishoweasyitistomakeacopyoftheitem.Ifyouhavealawnmower,andwantasecondlawnmower,thereisnomachinethatwillcopythelawnmower.Youcouldphotographthelawnmower,butyou'donlyhaveaflatphotographofalawnmower.Youcouldn'tmowanylawnswiththephoto.Togetarealsecondlawnmower,you'dhavetogobacktothelawnmowerfactoryandbuildanotheroneoutofironandplasticandropeandwhateverelselawnmowersaremadeoutof.Thisishardware.
Softwarecanbecopiedeasilybymachine.Allyouneedissomethingthatcanreadthediskorwhateveritisrecordedon,andsomethingelsetowriteitontoanewdisk.Thenewonewillbejustliketheoriginal,itwilldoallthesamethings.Iftheoriginalisyourfavoritemovie,thecopywillalsobeyourfavoritemovie.Iftheoriginalisaprogramthatwillprepareyourtaxpapers,sowillthecopy.
Softwareisnotaphysicalthing,itisjusthowthephysicalthingsareset.
Byfarthemostcommonlyuseddefinitionof'software'istorefertoapackageofcomputerinstructioncode.Ithinkthatthewayitgotthisnameisthatonceyouhavebuiltadeviceasversatileasacomputer,therearemanydifferentthingsthatitcanbemadetodo.Butwhentherearenoinstructionsinit,itcan'tdoanything.Sothesoftwareisanabsolutelynecessarypartofacomputerthatis
doingsometask.Itisavitalpartofthetotalmachine,yetitisn'tlikeanyotherpartinthemachine.Youcan'tweighitormeasureitorpickitupwithapairofpliers.Soitispartofthe'ware,'butitisn'thardware.Theonlythinglefttocallitis'software.'
Programs
Asmentionedearlier,aseriesofinstructionsinRAMarecalledaprogram.
Programscomeinmanysizes.Generally,aprogramisapieceofsoftwarethathaseverythingneededtodoaspecifictask.Asystemwouldbesomethinglarger,madeupofseveralprograms.Aprogrammightbemadeupofseveralsmallerpartsknownas'routines.'Routinesinturnmaybemadeupofsubroutines.
Therearenohardandfastdefinitionsthatdifferentiatebetweensystem,program,routineandsubroutine.Programisthegeneraltermforallofthem,theonlydifferenceistheirsizeandthewaytheyareused.
Thereisanotherdistinctionbetweentwotypesofprogramsthatisnotrelatedtotheirsize.Mosthomeandbusinesscomputershaveanumberofprogramsinstalledonthem.Mostoftheseprogramsareusedtodosomethingthattheownerwantstodo.Thesearecalledapplicationprogramsbecausetheyarewrittentoapplythecomputertoaproblemthatneedstobesolved.Thereisoneprogramonmostcomputersthatisnotanapplication.Itsjobistodealwiththecomputeritselfandtoassisttheapplicationprograms.ThisoneprogramthatisnotanapplicationiscalledtheOperatingSystem.
THEOPERATINGSYSTEM
An"OperatingSystem,"or"OS"forshort,isalargeprogramthathasmanypartsandseveralobjectives.
Itsfirstjobistogetthecomputerupandrunningwhenyoufirstturnthecomputeron.
Anotheroneofitsjobsistostartandendapplicationprogramsandgiveeachonetimetorun.Itisthe'boss'ofeveryotherprogramonthatcomputer.WhenmorethanoneprogramisinRAM,itistheoperatingsystemthatswitchesbetweenthem.Itletsoneprogramrunforasmallfractionofasecond,thenanotherprogram,thenanotherprogram.IftherearetenprogramsinRAM,andeachonegetstorunforonehundredthofasecondatatime,eachprogramwouldbeabletoexecutemillionsofinstructionsinthattime,severaltimespersecond.Itwouldappearthatalltenprogramswererunningsimultaneouslybecauseeachonegetstodosomething,fasterthantheeyecansee.
AnOperatingsystemalsoprovidesservicestoapplicationprograms.Whenanapplicationprogramneedstoreadfrom,orwritetothedisk,ordrawlettersonthescreen,itdoesnothavetodoallofthecomplicatedI/Oinstructionsnecessarytoaccomplishthetask.TheOShasanumberofsmallroutinesthatitkeepsinRAMatalltimesforsuchpurposes.
Allanapplicationneedstodotouseoneoftheseroutinesistoloadupsomeinformationintheregisters,andthenjumptotheaddressoftheproperOSroutine.Here'sanexampleofhowitmightbedone.Letssayyouwanttodrawacharacteronthescreen.First,puttheASCIIcodeofthedesiredcharacterintoR0.ThenputrowandcolumnnumbersofwhereyouwantittoappearonthescreenintoR1andR2.Andhere'sthetrickypart:Youputtheaddressofthenextinstructionofyourapplicationprogram,intoR3.NowjustjumptotheOSroutine.Theroutinewilltakecareofallofthedetailsofdrawingthecharacteronthescreen,andthenitslastinstructionwillbeJMPRR3.Thus,theseroutinescanbe'called'fromanyapplication,andwhendone,theroutinewilljumpbacktothenextinstructionintheapplicationthatcalledit.
ThereareseveralreasonsforhavingtheOSdoalloftheI/Ofunctions.Oneisthatitmakesiteasiertowriteapplicationprograms,theprogrammerdoesnotevenneedtoknowhowtheperipheralsactuallywork.AnotherreasonisthatitwouldwastealotofRAMifeveryapplicationhaditsowncopyofalloftheI/Oroutines.OneofthemostimportantreasonsisthattheOScanchecktosee
whethertheprogramshouldbeallowedtodowhatitisaskingtodo.ThisispartoftheOS'sotherjobofbeingtheboss.
TheheartoftheOSisbasicallyaloopofinstructionsthatasksthefollowingquestions:DoIneedtoinputanything?DoIneedtooutputanything?DoIneedtoletanyprogramrun?Thenitstartsoveragain.Iftheanswerstoallofthesequestionsisno,theCPUjustexecutestheinstructionsinthisloopoverandover,millionsoftimespersecond.Whenthereissomethingtodo,itjumpstothebeginningoftheprogramthattakescareofit,andwhenthatisdone,itjumpsbacktothisloopwheretheOS'waits'forsomethingelsetodo.
HereisadiagramofourlargerRAMversion,showingwhatpartsofRAMmightbeoccupiedbyanOperatingSystemandseveralotherprograms.
Withineachprogram'sRAM,thereisalloftheinstructioncodethatmakestheprogramwork.Eachprogrammaybedividedupintoitsownmainloop,andmanyroutinesthatareusedforthevarioustasksthatitneedstodo.Asmentioned,theOSalsohasroutinesthatcanbecalledbyotherprograms.
Eachprogramalsousespartofits'addressspace'forthedatathatitisworkingon.Thecalculator,forexample,needstohaveafewbyteswhereitstoresthenumbersthattheuserentersintoit.Solitaireneedssomebytesthatspecifywhichcardsareinwhichpositions.ThewordprocessorneedssomeRAMforalloftheASCIIcodesthatmakeupthedocumentyouareworkingon.TheOSalsoneedsbyteswhereitcanstorefonts,keeptrackofwhereapplicationprogramshavebeenloaded,receivethedatathatitreadsfromthedisk,andformanyotherpurposes.
Andsothisiswhatgoesoninsideyouraveragecomputer.TherearemanydifferentprogramsanddataareasinRAM.TheOSjumpstoaprogram,theprogramjumpstoaroutine,theroutinejumpstoasub-routine.EachprogramworksonitsdataorcalculatessomethingordoesanI/Ooperation.Aseachonefinishes,itjumpsbacktowhereitcamefrom.TheCPUexecutesoneinstructionfromoneprogramatatime,andiftheyarewrittenintelligently,eachprogramwillgetitsjobdonepiecebypiece,withoutinterferingwiththerest.
Ifourcomputerhadincludedan'interruptsystem'likewedescribedafewchaptersback,everytimesomeonepressedakeyonthekeyboardormovedthemouse,therewouldbeaninterruptthatwouldcallapartoftheOSthatdetermineswhichI/Odevicecausedtheinterrupt,andthencallstheproperroutinetotakecareofwhateveritwas.Whenthatwasdone,theCPUwouldcontinueonwiththenextinstructionofwhateverprogramhadbeenrunningwhentheinterrupthappened.
Thiscanallseemverycomplex,withsomanymillionsandbillionsofinstructionsbeingexecutedintheblinkofaneye.Therearewaysoforganizingprogramsandgoodprogrammingpracticesthatcanmakeitmuchmoreunderstandable.AstudyofthesewouldsimplifysoftwareinthesamemannerthatIhopethisbookhassimplifiedthehardware.Butthatwouldbethesubjectforanotherentirebook.
LANGUAGES
Writingprogramsisveryhardtodowhenyou'rejustwritingonesandzeros,butthatistheonlycodethattheCPU'understands.'
Whatisalanguage?Aspokenlanguage,suchasEnglish,isawaytorepresentobjects,actionsandideaswithsounds.Awrittenlanguageisawaytorepresentthesoundsofaspokenlanguagewithsymbolsonpaper.Soundslikeanothercode,andacoderepresentingacode.Wejustcan'tgetawayfromthesethings!
DoyourememberthatshorthandweusedwhenwewerelookingattheCPUinstructioncodeandthewiringintheControlSection?Well,thatisactuallysomethingmorethanjustahandytoolthatwasinventedforthisbook.Itisacomputerlanguage.Hereareafewlinesofit:
Acomputerlanguageisawaytorepresenttheinstructioncode.Itspurposeistomakeiteasiertowritecomputerprograms.
Inordertousethislanguage,youwritetheprogramyouwantwithASCIIcharacters,andsaveitintoafile.Thenyouloadaspecialprogramcalleda'compiler'intoRAMandjumptoitsfirstinstruction.ThecompilerwillreadtheASCIIfile,translateeachlineintotheInstructionCodethatitrepresents,andwritealloftheInstructionCodebytesintoasecondfile.ThesecondfilemaythenbeloadedintoRAM,andwhentheCPUjumpstoitsfirstinstruction,theprogramyouwroteinASCIIwillhopefullydowhatyouintendedittodo.
Ofcourse,whencomputerswerefirstinvented,allprogramshadtobewrittendirectlyinonesandzeros.Thensomebodygottiredofthetediumofprogrammingthatway,anddecidedtowritethefirstcompiler.Theneverafter,programswerewritteninthiseasierlanguage,andthentranslatedintoInstructionCodebythecompiler.Withtheoriginalcompiler,youcouldevenwriteabettercompiler.
Soinorderforacomputerlanguagetoexist,youneedtwothings,asetofwords
thatmakeupthelanguage(anothercode,)andacompilerthatcompilesthewrittenlanguageintocomputerinstructioncode.
Thelanguagethatwehaveseeninthisbookhasonlyabout20wordsinit.Eachwordcorrelatesdirectlytooneoftheinstructionsofwhichthiscomputeriscapable.Eachlineyouwriteresultsinonecomputerinstruction.Whenyouwritean87lineprograminthislanguage,theinstructioncodefilethatthecompilergenerateswillhave87instructionsinit.
Thensomeoneinventeda"higherlevel"languagewhereonelineofthelanguagecouldresultinmultiplecomputerinstructions.Forexample,ourcomputerdoesnothaveaninstructionthatdoessubtraction.Butthecompilercouldbedesignedsothatitwouldrecognizeanewwordinthelanguagelike'SUBRA,RB'andthengeneratehowevermanymachineinstructionswerenecessarytomakethesubtractionhappen.Ifyoucanfigureouthowtodosomethingfancywith47instructions,youcanhaveawordinyourlanguagethatmeansthatfancything.
Thensomeoneinventedanevenhigherlevellanguagewherethewordsthatmakeupthelanguagedon'tevenresembletheCPU'sactualinstructions.Thecompilerhasalotmoreworktodo,butstillgeneratesinstructioncodethatdoesthethingsthatthewordsinthatlanguagemean.Afewlinesfromahigherlevellanguagemightlooklikethis:
Balance=2,000InterestRate=.034Print"HelloJoe,yourinterestthisyearis:$"PrintBalanceXInterestRate
Thecompilerforthislanguagewouldreadthisfour-lineprogram,andgenerateafilethatcouldeasilycontainhundredsofbytesofinstructioncode.WhenthatinstructioncodewasloadedintoRAMandrun,itwouldprint:
HelloJoe,yourinterestthisyearis:$68
Writingsoftwareinhigherlevellanguagescanresultingettingalotmoredoneinashorteramountoftime,andtheprogrammernolongerneedstoknowexactlyhowthecomputeractuallyworks.
Therearemanycomputerlanguages.Somelanguagesaredesignedtodoscientificwork,somearedesignedforbusinesspurposes,othersaremoregeneralpurpose.Lowerlevellanguagesarestillthebestforcertainpurposes.
THEFILESYSTEM
Aswesawearlier,thewayadiskactuallyworksisprettyforeigntomostpeoplewhouseacomputer.
Tomakethingseasier,someoneinventedanideacalleda"file."Afileissupposedtobesimilartothekindofpaperfilesthatpeopleuseinoffices.Apaperfileisasheetofcardboardfoldedinhalfandplacedinafilecabinet.Thisfolderhasatabonitwhereyoucanwritesomesortofnameforthefolder,andthenyoucanputoneormanypiecesofpaperinthefolder.
Acomputerfileisastringofbytesthatcanbeanylength,fromonebyteuptoallofthebytesavailableonthedisk.Afilealsohasaname.Adiskmayhavemanyfilesonit,eachwithitsownname.
Ofcourse,thesefilesarejustanidea.Tomakeafilesystemwork,theoperatingsystemprovidesabunchofsoftwarethatmakesthediskappeartobelikeafilingcabinetinsteadofhavingheads,tracks,sectorsandblocksofbytes.
Thisfilesystemgivesapplicationprogramsaneasywayofusingthedisk.ApplicationscanasktheOStocreate,read,writeorerasesomethingcalledafile.Alltheapplicationneedstoknowisthenameofthefile.Youopenit,requestbytes,senditbytes,makeitbiggerorsmaller,closethefile.
TheOSusespartofthedisktomaintainalistoffilenames,alongwiththelengthofeachfileandthediskaddress(head,track,sector)ofthefirstsectorofthedata.Ifthefileissmallerthanadisksector,that'sallyouneed,butifthefileislargerthanonesector,thenthereisalsoalistwhichcontainsasmanydisk-typeaddressesasneededtoholdthefile.
Theapplicationprogramsayscreateafilewiththename"lettertoJane."ThentheusertypesthelettertoJaneandsavesit.TheprogramtellstheOSwheretheletterisinRAMandhowlongitis,andtheOSwritesittodiskinthepropersectororsectorsandupdatesthefilelengthandanynecessarylistsofdisk-typeaddresses.
Tousethefilesystem,therewillbesomesortofrulesthattheapplicationprogramneedstofollow.Ifyouwanttowritesomebytestothedisk,youwouldneedtotelltheOSthenameofthefile,theRAMaddressofthebytesthatyouwanttowrite,andhowmanybytestowrite.Typically,youwouldputallofthisinformationinaseriesofbytessomewhereinRAM,andthenputtheRAMaddressofthefirstbyteofthisinformationinoneoftheregisters,andthen
executeaJumpinstructionthatjumpstoaroutinewithintheOperatingSystemthatwritesfilestothedisk.Allofthedetailsaretakencareofbythisroutine,whichispartoftheOS.
IfyouasktheOStolookatyourdisk,itwillshowyoualistofallthefilenames,andusuallytheirsizesandthedateandtimewhentheywerelastwrittento.
Youcanstoreallsortsofthingsinfiles.Filesusuallyhavenamesthataremadeupoftwopartsseparatedbyaperiodlike"xxxx.yyy."Thepartbeforetheperiodissomesortofanamelike"lettertoJane,"andthepartafterthedotissomesortofatypelike"doc"whichisshortfor"document."Thepartbeforetheperiodtellsyousomethingaboutwhatisinthefile.Thepartafterthedottellsyouwhattypeofdataiscontainedinthisfile,inotherwords,whatcodeituses.
ThetypeofthefiletellsbothyouandtheOSwhatcodethedatainthefileuses.Inonepopularoperatingsystem".txt"meanstext,whichmeansthatthefilecontainsASCII.A".bmp"meansBitMaP,whichisapicture.A".exe"meansexecutable,whichmeansitisaprogramandthereforecontainsInstructionCode.
IfyouasktheOSwhatprogramsareavailabletoexecute,itwillshowyoualistofthefilesthatendwith".exe".Ifyouaskforalistofpicturesthatyoucanlookat,itwillshowyoualistoffilesthatendwith".bmp".
Therearemanypossiblefiletypes,anyprogramcaninventitsowntype,anduseanycodeorcombinationofcodes.
ERRORS
Thecomputerisafairlycomplexmachinethatdoesaseriesofsimplethingsoneafteranotherveryquickly.Whatsortsofthingscouldgowronghere?
Intheearlydaysofcomputing,wheneachgateinthecomputerwasrelativelyexpensivetobuild,sometimestherewerecomponentsthatactuallyhadmovingpartstomakeelectricalconnections.Twopiecesofmetalhadtotouchtomaketheelectricitygotowherethebuilderswantedittogo.Sometimeswhenthemachinestoppedworkingcorrectly,thefixitguywouldlookinsidetofindoutwhatwaswrong,andhewouldfindthataspiderhadcrawledinsidethemachineandhadgottenitselfwedgedinbetweentwoofthesepiecesofmetalthatweresupposedtotoucheachother.Thenwhenonepieceofmetalmovedtotouchtheother,thespiderwasinthewayandtheywouldn'ttouch.Sotheelectricitywouldn'tgettowhereitneededtogo,andthemachinewouldnotoperatecorrectlyanymore.Thefixitguywouldremovethebug,cleanupthecontacts,andreport"Therewasabuginthecomputer."Andheliterallymeantabug.
Overtime,wheneveracomputerappearedtobeoperatingincorrectly,peoplewouldsaythatthecomputerhadabug.Therearetwomainclassesofcomputerbugs:hardwareandsoftware.
Ahardwarebugactuallymeansthatthecomputerisbroken.Thiscouldbeasseriousasyouturnthecomputeron,anditcatchesfire,tothereisonebyteintheRAMwhereonebitisalwaysoff.
NowonebitinRAMthatrefusestochangemaybeaproblemoritmaynot.Ifthebytewherethatbitislocatedsomehownevergetsused,thenthecomputerwillworkjustfine.Ifthatbyteispartofaplacewhereanameisstored,thenthenamemaygetchangedfrom"Joe"to"Jod."Ifthatbytehassomeprograminstructionsinit,youmaygetanXORinstructionchangedtoaJMPinstruction.Thenwhentheprogramgetstothatinstruction,itwillnotdotheXORlikeitissupposedto,butratheritwilljumpsomewhereelseandstartexecutingwhateverisatthenewlocationasthoughitwasaseriesofinstructions.Thecontentsofthosebyteswilldeterminewhathappensnext,butitwillalmostcertainlybeaswrongasatrainfallingoffitstrack.
Ifagateisbrokeninthestepper,forinstance,sothatstep4nevercomeson,thenthecomputerwillnotreallybeabletooperateatall.Itwouldstillbeabletofetchinstructionsinsteps1,2and3,buteveryinstructionwouldexecuteincorrectly.Certainlytheprogramwouldmakeamessofthingsafter‘executing’
justafewinstructions.
Softwarebugscantakemanyforms,buttheyareallultimatelyprogrammermistakes.Thereareprobablymanymorewaystowriteaprogramincorrectlythancorrectly.Someerrorsjustcreatesomekindofincorrectresults,andothererrorscausethecomputerto“crash.”
Oneofmyfavoritestupidprogrammerstoriesisthis:Someoneboughtacaroncredit.Hegotacouponbookwiththeloan,onecoupontobesentinwitheachpayment.Butwhenhemadehisfirstpayment,heaccidentallyusedthelastcouponinthebookinsteadofthefirstone.Afewweekslater,hereceivedacomputer-generatedletterfromtheloancompanysaying,“Thankyouforpayingoffyourloaninfull,nexttimeyouneedaloanpleaseuseusagain.”Obviously,theprogramjustcheckedthecouponnumberandifitwasequaltothehighestnumbercouponinthebook,jumptotheroutineforapaid-in-fullloan.Itshouldhaveatleastcheckedthebalanceremainingontheloanbeforedecidingthatitwaspaidoff.Thisisasubtleerror,itmightnotbecaughtbytheloancompanyuntiltheyauditedtheirbooksmonthslater.Thecomputerdidexactlywhatitwastoldtodo,andmostofthetimeitwasadequate,buttheprogramwasnotwrittentoanticipateallofthesituationsthatsometimesoccurintherealworld.
Oneoftheworstsoftwarebugsisgettingstuckinaloop.Theprogramexecutesaseriesofinstructions,andthenjumpsbacktothebeginningoftheseriesandexecutesitoverandoveragain.Ofcourse,loopsareusedallthetimeinprogramming,buttheyareusedtodosomethingthathasafinitenumberofsimilarsteps.Itmayrepeatuntil50byteshavebeenmovedsomewhere,orkeepcheckingfortheusertopressakeyonthekeyboard.Butthecomputerwillexittheloopatsomepointandcontinueontoitsnexttask.Butifthereissomesortofprogrammingerrorwherethereisaloopthathasnowayout,thecomputerwillappeartobecompletelystuck.Thisissometimescalledbeing'hung,'thewholecomputermayneedtobeturnedoffandrestartedtogetoutoftheloopandbackintousefuloperation.
ThereareallsortsoferrorsthatendupwiththeCPUtryingtoexecutesomethingotherthaninstructioncode.Letssayyouhaveyourprogramresidingataddress10through150,andyouhavesomeASCIIdatasuchasnamesandphonenumbersataddresses151through210.Iftheprogramiswrittenincorrectlysothatundercertainconditionsitwilljumptoaddress180,itwilljustcontinuefetchingandexecutingthebytesstartingataddress180.If180-189wasfilledwiththeASCIIfor"JaneSmith,"the"program"willnowbeexecutingcompletegarbage,aseriesofbytesthatwerenotdesignedtobeInstruction
Code.Itmayputitselfintoaloop,orjumpbacksomewhereintotheprogram,orissuethecommandtoerasethediskdrive.Anditwillbedoinggarbageatitsusualhighspeed.Ifyoulookedatthepatternsinthebytes,youcouldseewhatitwoulddo,butitcouldbejustaboutanything.Ifthenameataddress180was"BillJones",itwoulddosomethingcompletelydifferent.Sinceitisnotdesignedtobeuseful,mostlikelyitwilljustkeepmakingabiggermessoutofwhatisinmemoryuntilthecomputerwillhavetobepoweredofftogetittostop.
Anothertypeoferrorcouldoccurifaprogramaccidentallywrote"JohnSmith"intotheplacewhereafontwasstored.Inthatcase,everyletter"E"thatgotdrawnonthescreenthereafterwouldlooklikethis:
Thecomputerexecuteshundredsofmillionsofinstructionseverysecond,anditonlytakesonewronginstructiontobringthewholethingtoascreechinghalt.Therefore,thesubjectofprogrammingcomputersinamannerthatwillbecompletely'bugfree'issomethingthatgetsalotofattention.Almostallprogrammingisdonewithlanguages,andthecompilersfortheselanguagesaredesignedtogenerateInstructionCodethatavoidsthemostserioustypesoferrors,andtowarntheprogrammerifcertaingoodprogrammingpracticesareviolated.Still,compilerscanhaveerrors,andtheywillneverbeabletospotanerrorliketheoneabovewiththecarloan.
Asyoucansee,thecomputeranditssoftwareareprettyfragilethings.Everygatehastoworkeverytime,andeveryinstructionthatgetsexecutedhastobecorrect.Whenyouconsiderallofthethingsthatcouldgowrong,thehighpercentageofthingsthatnormallygorightisactuallyquiteimpressive.
COMPUTERDISEASES?
Anotherplacewherehumancharacteristicsgetassignedtocomputersissomethingcalledacomputervirus.Thisimpliesthatcomputerscancomedownwithadiseaseandgetsick.Aretheygoingtostartcoughingandsneezing?Willtheycatchacoldorthechickenpox?Whatexactlyisacomputervirus?
Acomputervirusisaprogramwrittenbysomeonewhowantstodosomethingbadtoyouandyourcomputer.Itisaprogramthatwilldosomesortofmischieftoyourcomputerwhenitruns.Themotivationofpeoplewhowritevirusprogramsrangesfromthesimpletechnicalchallengeofseeingwhetheroneiscapableofdoingit,toadesiretobringdowntheeconomyofthewholeworld.Inanycase,thepeoplewhodosuchthingsdonothaveyourbestinterestsinmind.
Howdoesacomputer'catch'avirus?AvirusprogramhastobeplacedinyourRAM,andyourcomputerhastojumptothevirusprogramandrunit.Whenitruns,itlocatesafilethatisalreadyonyourharddisk,thatcontainsaprogramthatgetsrunonaregularbasisbyyourcomputer,likesomepartoftheoperatingsystem.Afterthevirusprogramlocatesthisfile,itcopiesthevirusprogramtotheendofthisfile,andinsertsajumpinstructionatthebeginningofthefilethatcausesajumptowherethevirusprogramis.Nowyourcomputerhasavirus.
Whenacomputerwithavirusisrunning,itdoesallofthethingsitissupposedtodo,butwheneveritrunstheprogramthatcontainsthevirus,theinsertedjumpinstructioncausesthevirusprogramtoberuninstead.Nowthevirususuallywilldosomethingsimple,likecheckforapredetermineddate,andifitisnotamatch,thenthevirusprogramwilljumpbacktothebeginningofthefilewheretheoperatingsystemprogramstillexists.
Thus,yourcomputerwillappeartotallynormal,therearejustafewextrainstructionsbeingexecutedduringitsregularoperations.Thevirusisconsidereddormantatthispoint.Butwhenthatdatearrives,andthevirus'decides'todowhateverisintherestofitsprogram,itcanbeanything.Whenthevirusprogramisrunning,itcandowhatevermischiefthepersonwhowroteitcouldthinkof.Itcanerasefilesonyourdisk,orsendthemsomewhereelseviatheinternet.Onehumorousviruswould,everyonceinawhile,makethelettersonthescreenappeartocomelooseandfallintoapileatthebottomofthescreen.
Here'sanexampleofhowtocatchavirus.Let'ssaythatyouhaveafriendwhofindsafunnymovieontheInternet.Itmakeshimlaugh,andhethinksthatyouwillenjoyittoo,soheemailsthemoviefiletoyou.Youreceivethemoviefile
andplayit,andyoudoenjoyit.
Therearetwodifferentthingsthatcouldhaveoccurredhere.Ifyourfriendsentyouafilenamed"funny.mov,"andyourOSincludesaprogramthatplays'.mov'files,thentheOSwillloadthatprogramintoRAM,andthatprogramwillreadthepicturesinthe"funny.mov"fileanddisplaythemonyourscreen.Thisisfine,theprogramthatranwassomethingthatwasalreadyonyourcomputer.The"funny.mov"filejustprovidedaseriesofpicturesthatweredisplayedonyourscreen.
Butifyourfriendsentyouafilenamed"funny.exe,"thenwhenyouasktheOStoplaythemovie,itwillload"funny.exe"intoRAMandjumptoitsfirstinstruction.Nowyouhaveaprogramrunninginyourcomputerthatcamefromsomewhereelse.Ifitisavirusprogram,itwillprobablyplaythemovieforyousothatyoudon'tsuspectanything,butitcandoanythingelsethatitwants,tothefilesonyourdiskwhileyouarewatchingthemovie.Itwillprobablyinstallitselfandgointoadormantstatefordaysorweeks,andyouwon'tevenknowthatyourcomputeris'infected.'Butsoonerorlateritwillcomealiveanddowhateverdamageitwasdesignedtodo.
Thissortofmaliciousprogramiscalledavirusbecausethewayitworksissimilartothewaythatrealvirusesinfectlivingthings.Arealvirusisathingthatissmallerthanaonecelledanimal.Itdoesn'tquitequalifyasbeingalivebecausethevirusbyitselfcannotreproduce.Theydoreproduce,however,byinvadingacellofsomethingthatisalive.Onceinthecell,thevirususesthemechanismsofthatcelltomakecopiesofitself,whichcanthengoonandinfectothercells.
Thecomputervirusalsocannotreproduceordoanythingelsebyitself.Itneedstogetintoacomputer,andsomehowgetitselfexecutedonetimebythatCPU.Whenitrunsthatfirsttime,itinsertsitselfsomewhereintotheoperatingsystemsothatitwillthereaftergetexecutedonaregularbasis.Thoseinstructionswilldowhateverdamagetheyaredesignedtodotothecomputeronwhichtheyarerunning,andtheywillalsousuallydosomethingthatisdesignedtospreadthevirustoothercomputers.
FIRMWARE
Ofcourse,RAMisanessentialpartofanycomputer.TheabilitytowritebytesintoRAM,andreadthembackoutagainisanintegralpartofhowthemachineworks.
Butinsomecomputers,therearesectionsoftheRAMthatonlygetwrittentowhenthecomputerstartsup,andthereafterthesesectionsremainunchangedasthecomputeroperates.Thiscouldbetrueinanycomputerthatalwaysrunsthesameprogram.PerhapshalfoftheRAMisusedtocontaintheprogram,andtheotherhalfoftheRAMisusedtocontainthedatathattheprogramisworkingon.Thehalfwiththeprogramhastobeloadedatsomepoint,butafterthat,theCPUonlyhastoreadthebytesoftheprograminordertofetchandexecutethem.
Whenyouhavethissortofsituation,youcanbuildhalfofyourcomputer'sRAMthenormalway,andwiththeotherhalf,youskiptheNANDgates,andjustwireeachbitdirectlytoanonoranoffinthepatternofyourprogram.
Ofcourse,youcan'twriteintothepre-wiredRAM,butyoucanreadfromitjustfine.ThistypeofRAMwasgiventhenameReadOnlyMemory,orROMforshort.YouuseitthesamewayyouuseRAM,butyouonlyreadfromit.
TherearetwoadvantagestoROM.Intheearlydaysofcomputers,whenRAMwasveryexpensive,ROMwasalotlessexpensivethanRAM.
TheotheradvantageisthatyounolongerhavetoloadtheprogramintoRAMwhenyoufirstturnthecomputeron.ItisalreadythereinROM,readytobeexecutedbytheCPU.
Thepointhereisanewword.Sincesoftwarewasnamed'soft'becauseitischangeable,whenitcomestoROM,youstillhaveapatterninthebits,butthey'renotsosoftanymore.Youcan'twriteintoaROM,youcan'tchangethebits.Andsothistypeofmemorycametobeknownas'firmware.'Itissoftwarethatispermanentlywrittenintohardware.
Butthatisn'ttheendofthestory.TheROMdescribedabovehadtobebuiltthatwayatthefactory.Overtheyears,thisideawasimprovedandmadeeasiertouse.
ThenextadvancewaswhensomeonehadthebrightideaofmakingROMwhereeverybitwassetonatthefactory,buttherewasawayofwritingtoitwithalotofpowerthatcouldburnoutindividualconnections,changingindividualbitsto
anoff.ThusthisROMcouldbeprogrammedafterleavingthefactory.Thiswascalled'ProgrammableROM'or'PROM'forshort.
ThensomeonefiguredouthowtomakeaPROMthatwouldrepairallofthosebrokenconnectionsifitwereexposedtoultravioletlightforahalfanhour.Thiswascalledan'ErasablePROM',or'EPROM'forshort.
ThensomeonefiguredouthowtobuildanEPROMthatcouldbeerasedbyusingextrapoweronaspecialwirebuiltintotheEPROM.Thiswascalled'ElectricallyErasablePROM',or'EEPROM'forshort.OneparticulartypeofEEPROMhasthename'Flashmemory.'
SothereisRAM,ROM,PROM,EPROM,EEPROMandFlash.Thesearealltypesofcomputermemory.Thethingtheyhaveincommonisthattheyallallowrandomaccess.Theyallworkthesamewaywhenitcomestoaddressingbytesandreadingoutthedatathatisinthem.ThebigdifferenceisthatRAMlosesitssettingswhenthepowergoesoff.Whenthepowercomesbackon,RAMisfullofallzeros.Therestofthemallstillhavetheirdataafterpoweroffandbackon.
Youmayaskthen,"Whydon'tcomputersuseEEPROMfortheirRAM?ThentheprogramwouldstayinRAMwhenthecomputerwasoff."TheansweristhatittakesmuchlongertowriteintoEEPROMthanRAM.Itwouldslowthecomputerdowntremendously.IfsomeonefiguresouthowtomakeanEEPROMthatisasfastandascheapandusesthesameorlesspowerasRAM,I'msureitwillbedone.
Bytheway,thewordROMhasalsocometobeusedtomeananytypeofstoragethatispermanentlyset,suchasaprerecordeddisk,asin'CDROM,'butitsoriginaldefinitiononlyappliedtosomethingthatworkedjustlikeRAM.
BOOTS
Whatdobootshavetodowithcomputers?Well,thereisanoldphrasethatgoes"pullyourselfupbyyourownbootstraps."Itiskindofajoke,itliterallyreferstothestrapsthataresewnintomanybootsthatareusedtohelppullthebootsontoyourfeet.Thejokeisthatifyouarewearingsuchapairofboots,andwanttogetupofftheground,insteadofgettingaladderorclimbingarope,youcangetyourselfoffthegroundbysimplypullinghardenoughonthosebootstraps.Ofcoursethiswouldonlyworkinacartoon,butthephrasehascometomeandoingsomethingwhenthereisnoapparentwaytodoit,ordoingsomethingwithoutthetoolsthatwouldnormallybeused,oraccomplishingsomethingbyyourselfwithouthelpfromanyoneelse.
Inacomputer,thereisaproblemthatissimilartoneedingtogetoffthegroundandhavingnotoolsavailabletoaccomplishit.Whenacomputerisoperating,thememoryisfullofprogramsthataredoingsomething,andwhentheoperatorofthecomputerentersacommandtostartanotherprogram,theoperatingsystemlocatestheprogramondisk,loadsitintomemory,andjumpstothefirstinstructionoftheprogram.Nowthatprogramisrunning.
Butwhenyoufirstturnonacomputer,howdoyougettheoperatingsystemintomemory?Ittakesaprogramrunninginmemorytotellthediskdrivetosendoversomeinstructioncode,andtheprogramneedstowritethatcodeintomemoryatanappropriateplace,andthenjumptoitsfirstinstructiontogetthenewprogramrunning.Butwhenyouturnthecomputeron,everybyteinmemoryisallzeros.Therearenoinstructionsinmemoryatall.Thisistheimpossiblesituation,youneedaprograminmemorytogetaprograminmemory,butthereisnothingthere.Soinorderforthecomputertogetgoinginthefirstplace,thecomputerhastodosomethingimpossible.Ithastopullitselfupbyitsbootstraps!
Alongtimeago,intheearlydaysofcomputers,themachinehadswitchesandpushbuttonsonthefrontpanelthatallowedtheoperatortoenterbytesofdatadirectlyintotheregisters,andfromthere,intoRAM.Youcouldmanuallyenterashortprogramthisway,andstartitrunning.Thisprogram,calleda"bootstraploader,"wouldbethesmallestpossibleprogramyoucouldwritethatwouldinstructthecomputertoreadbytesfromaperipheral,storetheminRAM,andthenjumptothefirstinstruction.Whenthebootstraploaderexecutes,itloadsamuchlargerprogramintomemory,suchasthebeginningsofanoperatingsystem,andthenthecomputerwillbecomeusable.
Nowadays,therearemucheasierwaysofloadingthefirstprogramintothecomputer,infactithappensautomaticallyimmediatelyafterthecomputergetsturnedon.Butthisprocessstillhappens,andthefirststepiscalled"booting"or"bootingup"anditonlymeansgettingthefirstprogramintomemoryandbeginningtoexecuteit.
Themostcommonsolutiontothisproblemhasthreeparts.First,theIARisdesignedsothatwhenthepowerisfirstturnedon,insteadofallofitsbitsbeingzero,itslastbitwillbezero,buttherestofitsbitswillbeones.Thusforourlittlecomputer,thefirstinstructiontobefetchedwillbeataddressmimo.Second,somethinglikethelast32bytesoftheRAM(235-256)willbeROMinstead,hardwiredwithasimpleprogramthataccessesthediskdrive,selectsheado,tracko,sectoro,readsthissectorintoRAM,andthenjumpstothefirstbyteofit.Thethirdpartthen,hadbetterbethatthereisaprogramwrittenonthatfirstsectorofthedisk.Thissector,bytheway,iscalledthe'bootrecord.'
Thisword'boot'hasbecomeaverbincomputertalk.ItmeanstoloadaprogramintoRAMwheretherearenoprograms.SometimespeopleuseittomeanloadinganyprogramintoRAM,butitsoriginalmeaningonlyappliedtoloadingthefirstprogramintoanotherwiseblankRAM.
DIGITALVS.ANALOG
You'venodoubtheardthesetermsbandiedabout.Itseemsthatanythingassociatedwithcomputersisdigital,andeverythingelseisnot.Butthat'snotquitecloseenoughtothetruth.
Whattheymeanisquitesimple,butwheretheycamefromandhowtheyendedupintheircurrentusageisnotsostraightforward.
Theword'digital'comesfromdigit,whichmeansfingersandtoesinsomeancientlanguage,andsincefingersandtoeshavebeenusedforcounting,digitalmeanshavingtodowithnumbers.Today,theindividualsymbolsthatweusetowritenumbers(o,1,2,3,etc.)arecalleddigits.Inthecomputer,werepresentnumberswithbitsandbytes.Oneofthequalitiesofbitsandbytesistheirunambiguousnature.Abitiseitheronoroff;thereisnograyareainbetween.Abyteisalwaysinoneofits256states;thereisnostatebetweentwonumberslike123and124.Thefactthatthesestateschangeinstepsiswhatwearereferringtowhenwesaydigital.
Theword'analog'comesfromthesameplaceas'analogy'and'analogous,'thusithastodowiththesimilaritybetweentwothings.Intherealworld,mostthingschangegraduallyandcontinuously,notinsteps.Avoicecanbeashoutorawhisperorabsolutelyanywhereinbetween.Whenatelephoneconvertsavoiceintoanelectricalequivalentsothatitcantravelthroughawiretoanothertelephone,thatelectricitycanalsovaryeverywherebetweenbeingfullyonandfullyoff.Soundandelectricityaretwoverydifferentthings,buttheessenceofthevoicehasbeenduplicatedwithelectricity.Sincetheyaresimilarinthatrespect,wecansaythattheelectricalpatternisan'analog'ofthevoice.Althoughthemeaningof'analog'comesfromthis'similarity'factor,whenyoumakeananalog,youareusuallymakingananalogofsomethingthatiscontinuouslyvariable.Thisideaofsomethingbeingcontinuouslyvariablehascometobethedefinitionofanalogwhenyouarecomparingdigitalandanalog.Somethingthatisanalogcanbeanywherewithintheentiretyofsomerange,therearenosteps.
Digitalmeanschangebystepsandanalogmeanschangeinasmoothcontinuousmanner.Anotherwaytosayitisthatdigitalmeansthattheelementsthatmakeupawholecomefromafinitenumberofchoices,whereasanalogmeansthatathingismadeofpartsthatcanbeselectedfromanunlimitednumberofchoices.Afewnon-computerexamplesmayhelptoclarifythis.
Ifyouhaveaplatformthatisthreefeetabovethefloor,youcaneitherbuildstairsforpeopletoclimbuptoit,oraramp.Ontheramp,youcanclimbtoanylevelbetweenthefloorandtheplatform;onthestairs,youonlyhaveasmanychoicesastherearesteps.Therampisanalog,thestairsaredigital.
Let'ssaythatyouwanttobuildawalkwayinyourgarden.Youhaveachoiceofmakingthewalkwayoutofconcreteoroutofbricks.Ifthebricksarethreeincheswide,thenyoucanmakeabrickwalkthatis30incheswide,or33incheswide,butnot31or32.Ifyoumakethewalkoutofconcrete,youcanpourittoanywidthyouwant.Thebricksaredigital,theconcreteisanalog.
Ifyouhaveanoldbookandanoldoilpainting,andyouwanttomakeacopyofeach,youwillhaveamucheasiertimemakingacopyofthebook.Evenifthepagesofthebookareyellowed,andthecornersaredog-eared,andtherearedirtsmudgesandwormholesinside,aslongasyoucanreadeveryletterinthebook,youcouldre-typetheentiretext,exactlyastheauthorintendedit.Withtheoilpainting,theoriginalcolorsmayhavefadedandareobscuredbydirt.Theexactplacementofeachbristleineachbrushstroke,thethicknessofthepaintateveryspot,thewayadjacentcolorsmix,couldallbecopiedingreatdetail,buttherewouldinevitablybesomeslightdifferences.Eachletterinthebookcomesfromalistofaspecificnumberofpossibilities;thevariationsofpaintcolorsandtheirpositionsonthecanvasarelimitless.Thebookisdigital,thepaintingisanalog.
Sothereyouhavethedifferencebetweenanaloganddigital.Theworldaroundusismostlyanalog.Mostoldtechnologieswereanalog,likethetelephone,phonograph,radio,television,taperecordersandvideocassettes.Oddlyenoughthough,oneoftheoldestdevices,thetelegraph,wasdigital.Nowthatdigitaltechnologyhasbecomehighlydevelopedandinexpensive,theanalogdevicesarebeingreplacedonebyonewithdigitalversionsthataccomplishthesamethings.
Soundisananalogthing.Anoldfashionedtelephoneisananalogmachinethatconvertsanalogsoundintoanelectricalpatternthatisananalogofthesound,whichthentravelsthroughawiretoanotherphone.Anewdigitaltelephonetakestheanalogsound,andconvertsitintoadigitalcode.Thenthedigitalcodetravelstoanotherdigitalphonewherethedigitalcodeisconvertedbackintoanalogsound.
Whywouldanyonegotothetroubleofinventingadigitalphonewhentheanalogphoneworkedjustfine?Theanswer,ofcourse,isthatalthoughtheanalogphoneworked,itwasnotperfect.Whenananalogelectricalpattern
travelsoverlongdistances,manythingscanhappentoitalongtheway.Itgetssmallerandsmallerasittravels,soithastobeamplified,whichintroducesnoise,andwhenitgetsclosetootherelectricalequipment,someofthepatternfromtheotherequipmentcangetmixedintotheconversation.Thefartherthesoundgoes,themorenoiseanddistortionareintroduced.Everychangetotheanalogofyourvoicebecomesapartofthesoundthatcomesoutattheotherend.
Enterdigitaltechnologytotherescue.Whenyousendadigitalcodeoverlongdistances,theindividualbitsaresubjectedtothesametypesofdistortionandnoise,andtheydochangeslightly.However,itdoesn'tmatterifabitisonly97%oninsteadof100%.Agate'sinputonlyneedsto'know'whetherthebitisonoroff,ithasto'decide'betweenthosetwochoicesonly.Aslongasabitisstillmorethanhalfwayon,thegatethatitgoesintowillactinexactlythesamewayasifthebithadbeenfullyon.Therefore,thedigitalpatternattheendisjustasgoodasitwasatthebeginning,andwhenitisconvertedbacktoanalog,thereisnonoiseordistortionatall,itsoundslikethepersonisrightnext-door.
Thereareadvantagesanddisadvantagestoeachmethod,butingeneral,thebenefitsofdigitaltechnologyfaroutweighitsshortcomings.
Probablythebiggestadvantageofdigitalhastodowiththemakingofcopies.Whenyoumakeacopyofsomethinglikeavinylrecord,youcouldrecordittoataperecorder,orIguessyoucouldevengetalloftheequipmenttocutanewvinylrecord.Buttherewillbesomedegreeofdifferencebetweentheoriginalandthecopy.Inthefirstplace,allmachineryhasaccuracylimitations.Acopyofanyphysicalobjectcanbeveryclosetotheoriginal,butneverquiteexact.Second,ifthereareanyscratchesorparticlesofdustontheoriginal,thecopywillthenhaveduplicatesofthesedefects.Third,frictionbetweentherecordandtheneedleactuallywearsawayatinyamountofvinyleverytimeyouplayit.Ifyouuseataperecorder,thereisalwaysalowlevelof'hiss'addedtothesound.Ifyoumakeacopyofacopy,andacopyofthat,etc.thechangeswillgetlargerandlargerateachstage.
Whenitcomestosomethingthatisdigital,aslongaseverybitthatwasonintheoriginalisalsooninthecopy,wegetanexactcopyeverytime.Youcanmakeacopyofthecopy,andacopyofthat,etc.,andeveryoneofthemwillbeexactlythesameastheoriginal.Digitalisdefinitelythewaytogoifyouwanttobeabletomakeanunlimitednumberofcopiesandpreservesomethingforalltime.
Thecomputerandperipheralswehavebuiltareentirelydigitalsofar.Andifallweeverwantedtodowiththemweredigitalthingssuchasarithmeticand
writtenlanguage,wecouldleaveitthatway.However,ifwewantourcomputertoplaymusicandworkwithcolorphotographs,thereisonemorethingweneedtolookat.
ILIED-SORTOF
ThereisonepieceofhardwareinacomputerthatisnotmadecompletelyoutofNANDgates.Thisthingisnotreallynecessarytomakeacomputeracomputer,butmostcomputershaveafewofthem.Theyareusedtochangefromsomethingthatisanalogtosomethingthatisdigital,ordigitaltoanalog.
Humaneyesandearsrespondtoanalogthings.Thingsthatwehearcanbeloudorsoft,thingsthatweseecanbebrightordarkandbeanyofamultitudeofcolors.
Thecomputerdisplayscreenthatwedescribedabovehad320x200or64,000pixels.Buteachpixelonlyhadonebittotellitwhattodo,tobeonoroff.Thisisfinefordisplayingwrittenlanguageonthescreen,oritcouldbeusedtomakelinedrawings,anythingthatonlyhastwolevelsofbrightness.Butwehaveallseenphotographsoncomputerscreens.
Firstofall,thereneedstobeawaytoputdifferentcolorsonthescreen.Ifyougetoutamagnifyingglassandlookatacolorcomputerortelevisionscreen,youwillseethatthescreenisactuallymadeupoflittledotsofthreedifferentcolors,blue,red,andgreen.Eachpixelhasthreepartstoit,oneforeachcolor.Whenthedisplayadapterscansthescreen,itselectsallthreecolorsofeachpixelatthesametime.
Foracomputertohaveacolorscreen,itneedstohavethreebitsforeachpixel,soitwouldhavetohavethreetimestheRAMinordertobeabletocontrolthethreecolorsineachpixelindividually.Withthreebits,eachcolorcouldbefullyonoroff,andeachpixelwouldthereforehaveeightpossiblestates:black,green,red,blue,greenandred(yellow,)greenandblue(cyan,)blueandred(magenta)andgreen,blueandred(white.)
Butthisisstillnotenoughtodisplayaphotograph.Todothat,weneedtobeabletocontrolthebrightnessofeachcolorthroughouttherangebetweenfullyonandfullyoff.Todothis,weneedanewtypeofpartthatwewilldescribeshortly,andweneedmorebitsinthedisplayRAM.Insteadofonebitforeachcolorineachpixel,wecouldhaveawholebyteforeachcolorineachpixel.That’sthreebytesperpixel,foratotalof192,000bytesofRAMjustforthissmalldisplayscreen.
Withthesebytes,usingthebinarynumbercode,youcouldspecify256levelsofbrightnessforeachcolorineachpixel.Thiswouldamountto16,777,216
differentstates(orcolors)foreachpixel.Thisisenoughvarietytodisplayareasonablygood-lookingphotograph.
Inordertomakethiswork–anumberspecifying256differentlevelsofbrightness–youneedathingcalleda“digitaltoanalogconverter”or“DAC”forshort.ADAChaseightdigitalinputs,andoneanalogoutput.Thewayitworksisthatitiswireduptotreattheinputasabinarynumber,andtheoutputhas256levelsbetweenoffandon.Theoutputhas256gradationsbetweenoffandon,anditgoestothelevelthattheinputnumberspecifies.Iftheinputisa128,theoutputwillbehalfwayon.Fora64theoutputwillbeonequarteron.For0,theoutputwillbefullyoff.
Inordertomakethiscolorscreenwork,thedisplayadapterneedstoaccessthreebytesatatime,connectthemtothreeDACs,andconnecttheoutputsoftheDACstothethreecolorsinthecurrentpixelbeingpainted.That’showacolorscreenworks.
Whenwedefined‘analog’inthelastchapter,wesaidthatitwassomethingthatwascontinuouslyvariablefromfullyofftofullyon.ButourDACreallyonlyhas256differentlevelsatits‘analog’output.It’salotclosertobeinganalogthanabit,butitstillhassteps.Whatthecomputerisdoingisapproximatingananalogthinginstepssmallenoughtofooltheintendedaudience.Whenitcomestotheeye,256differentlevelsofbrightnessissufficient.
Ifsomethingrequiressmallerstepstofooltheintendedaudience,youcanmakeaDACthathas16bitsonthedigitalside.Thusyoucanpresentthedigitalinputwithanumberanywherefromoto65535.Theanalogsidecanstillonlyvaryfromfullyofftofullyon,butthesizeofthestepswillbemuchsmallersincetherearenow65536ofthem.
Whenitcomestotheear,itcanhearverysmalldifferences,andsoa16bitDACisrequiredforhighqualitysound.
Allsounds,frommusictospeechtothundercrashesarevibrationsoftheair.Theyvaryinhowfasttheairvibrates,andinexactlyhowitvibrates.Thehumanearcanhearvibrationsfromabout20Hzatthelowendto20,000Hz(20kHz)atthehighend,sothisistherangeofvibrationsthatcomputersaredesignedtodealwith.Foranyelectronicmachinetomakesounds,thereisadevicecalledaspeaker.Allthataspeakerdoesismovebackandforthintheair,makingtheairvibrate.Ifitmakestheairvibrateinpreciselythesamewayastheoriginalthingthatwasrecorded,itwillsoundjustliketheoriginal.
Inordertostoreasoundinacomputer,thepositionofthespeakerisdividedinto65536possiblepositions.Thenasecondisdividedinto44,100parts.Ateachoneofthosepartsofasecond,thedesiredpositionofthespeakerisstoredasatwo-bytenumber.Thisisenoughinformationtoreproducesoundwithveryhighquality.
Toplaytopqualitystereomusic,acomputerwouldneeda'soundperipheral.'Thiswouldhavetwo16bitDACswiththeiranalogoutputsconnectedtospeakers.Itwouldalsohaveitsownclockthatticksat44,100Hz.Ateachtick,itwouldgetthenexttwotwo-bytenumbers,andconnectthemtothedigitalsideoftheDACs.
Asfarasspeedgoes,thiswouldbe176,400bytespersecond.Certainlythatisfast,butrememberthatourcomputerclockticksabilliontimespersecond.Thatmeansthatthecomputercansendfourbytestothesoundperipheral,andgooffandexecuteabout4000instructionsonsomeothertaskbeforeitneedstosendthenextfour.
Forgoingtheotherway,thereisan“AnalogtoDigitalConverter,”or“ADC”forshort.Thisisusedtoconvertthesoundfromamicrophoneintoaseriesofbytes,orforacameratoconvertapictureintoaseriesofbytes.Theinputhasonewirethatcanbeanywherefromallthewayofftoallthewayon.TheADCmakesitsoutputsintoanumberfrom0-255foran8-bitADCorfrom0-65,535fora16-bitADC.Thisnumberrepresentshowmuchtheinputisonoroff.Halfonis128or32,768,onequarteronis64or16,384,etc.ThisprocessisjustthereverseofwhataDACdoes.
DACsandADCsarenotmadeoutofNANDgates,theyhaveelectronicpartslikeradioshave.Howtheydowhattheydoisnotapropersubjectforthisbook.SomaybeIliedwhenIsaidthateverythinginacomputerismadeoutofNANDgates?Well,notreally,becauseDACsandADCsareonlyusedincertaintypesofperipherals,notinthecomputeritself.
FULLDISCLOSURE
Wehavebuiltaverysmallcomputerhere.Itisaboutthesmallestcomputerthatcouldbeinventedthatdoeseverythingnecessarytobeworthyofthenamecomputer.Idon'tthinkthatanyonehasbuiltsuchasmallcomputersinceabout1952,andnoonehaseverbuiltthisexactcomputerintherealworld.
Ifarealcomputerdesignereverreadthisbook,I'msurehe'dbepullinghishairoutoveralloftheopportunitiesthathavebeenmissedheretomakeabettermachine.Butagain,thegoalhasbeentoillustratecomputerprinciplesassimplyaspossible.
Thisisaneight-bitcomputer.Thatmeansthattheregistersintheprocessorareeightbits,thebusiseightbits,andinthismachine,eventheMemoryAddressRegisteriseightbits.
Withmostofthecomputersthatactuallygetbuilt,whiletheindividualbytesinRAMremain8bits,everythingelseisexpandedto16bits,32bitsor64bitsoracombinationoftheseindifferentpartsofthemachine.
OurRAMonlyhas256bytes,whichisridiculouslysmall,butthat'sallyoucanhavewithaneight-bitMemoryAddressRegister.Ifyouuse16bits,youcanhave65,536bytesofRAM(that's64kb),ifyouuse24bitsyoucanhave16mb,ifyouuse32bitsyoucanhave4gigabytesofRAM.
Realcomputershavethingsthatthisonedoesnot,buttheyarenotcapableofdoingthingsthatthiscomputercannotdo.
Inourcomputer,ifyouwanttoshiftabytethreebitstotheleft,youwouldputthreeshiftleftinstructionsinyourprogram.Inmostrealcomputers,theyhaveshiftersthatwillshiftanynumberofbitsinoneinstruction.Buttheresultisthesame,yourbyteendsuplookingthesameineithercase,therealcomputerjustgetsthejobdonefaster.
Inourcomputer,theaddercanaddtwoeight-bitnumbers.Ifyouwanttoadd16bitnumbers,youhavetoemploysomesoftwaretodoit.Inmostcomputers,theaddercanadd16or32bitnumbersinoneinstruction.Again,theresultsarethesame,oneisjustfasterthantheother.
Thestepperinourcomputerisasimplificationofsomethingthatmostcomputershave,calleda'statemachine.'Statemachinesprovidesteps,butstartthenextinstructionassoonaspossible,dowhatisnecessaryforaninterrupt
system,cancreatemorecomplexinstructions,etc.Sinceallweneededwassixconsecutivesteps,webuiltasimplerthingandjustmadeuptheterm'stepper.'
Soyes,ourcomputerisasimple,small,relativelyslowcomputer,butitcandoeverythingthatmorecomplicatedmachinescando.Thethingsthatmakeabiggermachinebigger,aredesignedtogetthejobdonefaster,doitinfewerclockcycles,dothesametaskwithfewerinstructions,operateonseveralbytesatthesametime.Butthenatureofwhatthemachinesdoisexactlythesame.Everytasktheycandocomesdowntoshifting,ANDing,ORing,XORing,ADDingandNOTingbytes.Therearenootherfancytypesofoperationsthathavebeenleftoutofthisbook.
Inabiggermachine,youcandoaddition,subtraction,multiplicationanddivisioninasingleinstruction.Thatisbecausetheyhavehugenumbersofgatesarrangedintothingslikea'hardwaremultiplier.'Thereisnoreasontoshowyouthedetailsofhowyouconstructoneofthese,itisaverycomplicatedjobforthefewpeoplewhoneedtobuildone.Itisunderstandable,anditallultimatelycomesdowntoNANDgatesjustlikeeverythingelse.Butwehaveseenhowtodoallthemathoperationstherearewithjustanadder,shifter,NOTgatesandsomesoftware.Thehardwaremultipliergetstherefaster,buttheresultsareexactlythesame.
Biggermachineshavemoreregisters,theregistersareeachmultiplebytes,theyhaveaddersthatcanaddthreenumbersatthesametime,butstilltheinstructionscomedowntothesamesimpleoperations.Yourunderstandingofcomputersisnotsmallbecausewehavelookedatasmallcomputer.
PHILOSOPHY
Whydowehaveachaptercalled"Philosophy"inabookaboutcomputers?Theonlythinginthisbookthatevencomesclosetobeingaphilosophicalquestionisitstitle,"ButHowdoitKnow?"Wewillattempttoanswerthisquestionalittlelateron.
Thisbookhasbeenaboutthecomputersthatwehavetoday.Butwhataboutthefuture?Ascomputersandsoftwarecontinuetoadvance,howsoonifever,willthedaycomewhentherearewalkingtalkingcomputerizedrobotsthatlookandactjustlikepeople?Willthedaycomewhenwehavetodecidewhetherornottogivetheserobotsthesamelegalrightsaspeople?Willcomputerseventuallytakeovertheworldandreplacepeoplealtogether?
Toanswerthesesortsofquestions,peopleoftenrefertoamajorquestionthathasbeenoutstandinginthefieldofphilosophyformanyyears.
Thequestionis,whethermaniscomposedsolelyofthestructuralbodythatwecanseeanddissect,orwhetherthereisanintegralspiritualcomponenttoeveryhumanbeingwhichaccountsforthequalitiesofconsciousness,love,honor,happiness,pain,etc.
Thatquestionisfarbeyondthescopeofthisbook,anditremainsunconvincinglyanswereddespitemanybooksarguingeachviewpoint.Therearepeopleinthescienceswhosaythatweareontracktobuildingconsciouscomputers,anditwillhappen.Therearepeopleinthehumanitieswhosaythatitisimpossiblebecauseyoucan'tmanufactureaspirit.Eachsidehasbeenunabletoswaytheother.
Ifwedefinethebrainasthatfunnylookingchunkofgraymeatenclosedbytheskull,anddefinethemindaswhateveritisthatisresponsibleforconsciousness,memory,creativity,thinking,andeverythingelsethatwenoticegoingoninourheads,thenwecanrestatethebigphilosophicquestionas:"Arethebrainandthemindoneandthesamething?"
Thenwhenitcomestothequestionaboutbuildingaconvincinghumanrobot,therewouldbetwopossibilities.
Ifthebrainandthemindarethesamething,youmightnotbeabletobuildasyntheticpersontoday,butastimewenton,eventuallyyoucouldunderstandeverystructureandfunctioninthebrain,andbuildsomethingofequalcomplexitythatwouldgeneratetrueconsciousness,andthatreallyshouldact
justlikeanyotherperson.
Ifthebrainandthemindarenotthesamething,thenbuildingarobotbuddywillalwaysbeaboutsimulatinghumanity,notbuildingsomethingofequalqualityandvalue.
Restatingthequestiondoesn'tmakeitanyeasiertoanswer,butthisideaofseparatingwhatweknowaboutmindsfromwhatweknowaboutbrainsmaybeuseful.Earlyon,wesaidthatweweregoingtoshowhowcomputersworksothatwecouldseewhattheywerecapableofdoing,andalsowhattheywerenotcapableofdoing.Wearegoingtotakewhatweknowaboutbrainsandwhatweknowaboutmindsandcompareeachindividuallytoournewknowledgeaboutcomputers.Indoingsowecanlookfordifferencesandsimilarities,andwemaybeabletoanswerafewlesscontroversialquestions.
Computersdocertainthingswithgreatease,suchasaddingupcolumnsofnumbers.Acomputercandomillionsofadditionsinasinglesecond.Themindcanbarelyremembertwonumbersatthesametime,nevermindaddingthemupwithoutapencilandpaper.
Themindseemstohavetheabilitytolookatandconsiderrelativelylargeamountsofdataatthesametime.WhenIthinkofmyfavoritecat,Icanre-experienceseeingwhathelookslike,hearingthesoundsofhispurringandmewing,feelingthesoftnessofhisfurandhisweightwhenpickedup.ThesearesomeofthewaysthatIknowmypet.
Whatwoulditmeanforourcomputertothinkaboutacat?ItcouldhavepicturesofthecatandsoundsofthecatencodedinfilesonaspinningdiskorinRAM.Isthatthinking?IfyouranthebytesofthesefilesonebyonethroughtheALU,wouldthatbethinking?Ifyouputthepictureonthescreen,wouldthatbethinking?Ifyouplayedthesoundstothespeakers,wouldthatbethinking?
Thesoundsandpicturesencodedinthecomputerarejustbytepatternssittingwheretheyare.Theydon'tlooklikeanythingorsoundlikeanythingunlesstheyaresenttotheperipheralsforwhichtheyweredesigned.Andiftheyaresenttothescreenandspeakers,thecomputerdoesn'tseethemorhearthem.Ofcourse,yourcomputercouldhaveacamerapointingatthescreen,andamicrophonelisteningtothesounds,butthecomputerstillwouldn'tseeapictureorhearasound,itwouldjustcollectmorestringsofbytesverysimilartotheonessenttothescreenandspeakersinthefirstplace.
Therecouldbeprogramsthatperformmathematicaloperationsonthepicturefilesinordertodiscoverpatterns,andstoretheresultsofthesecalculationsinotherfiles.Therecouldbefilesthatrelateonepicturefiletoothersimilarpicturefiles,andpicturestosounds,etc.,creatingmorefiles.
Butnomatterhowmuchprogrammingisappliedtothepicturefiles,thereissomethingthatthemindcandothatthecomputersimplydoesn'thaveanyfacilityfor.
Themindcanconsiderthewholeofsomethingallatthesametime.Youcanthinkofthewholeofthecatallatonce.ItssortoflikethedifferencebetweenthemoviefilmandtheTVscreen.Themoviefilmhaswholepictures,theTVscreenonlyhasonepixelatatime.Youcouldsaythatyourmindworkssoquicklythatyoudon'tnoticethedetails,itgetsintegratedintoawholejustlikethepixelsgetintegratedintoanentirepicture.Butwhatdoestheintegrating?Andwhenit'sintegrated,whatisitandwhereisit?Andwhatlooksattheintegratedwhole?
We'vejustseeneverythingthat'sinacomputer.Thecomputermovesonebyteatatimeoverthebus.Thefanciestthingitdoesistoaddtwobytesintoone.Everythingelseit'does'amountstonothingmorethanthesimplewarehousingofbytes.Astoredbytedoesn'tdoanythingbeyondmaintainingitsowncurrentsetting.Acomputerjustdoesn'thaveanyfacilitiesthatintegratetheelementsofapictureintoanythingelse,nowheretostorethatsomethingelse,andnothingwithwhichtolookatit.
I'mnotsayingthatsomethingcouldn'tbebuiltthatwouldperformthesefunctions,I'mjustsayingthatcomputersasweknowthemtodaydon'tcurrentlyincludeanysuchdevice.
Hereisanotherquestion.Ifabrainworkslikeacomputer,thenitneedstohaveaprogramfortheCPUtorun.Wherewouldthisprogramcomefrom?
Althoughthebrainhastrillionsofcells,theentirehumanbodystartswithonefertilizedeggcell.Soanyprogramthatthebrainhas,wouldhavetobepresentinthissinglecell,presumablyintheDNA.
ScientistshavenowdecodedtheentireDNAsequenceofhumans.DNAisinterestinginthatitisalongstringofonlyfourtypesofthings.It'sdigital!Alotofthepiecesofthisstringareusedformakingchemicalreactionstakeplacetomakeproteins,etc.butthemajorityofitiscalled'junkDNAbecausenooneknowswhatitspurposeis.ButevenifyouconsiderthattheentiretyoftheDNA
isdevotedtocomputersoftware,thentherecouldbeaboutabillioninstructionsinthisprogram.Nowthat'salotofsoftware,buttheaveragehomecomputerprobablyhasthatmuchsoftwareloadedontoit'sharddrive,andthatwouldn'tbeanywherenearenoughtorunahumanbeing.
Somehavesaidthatthehumancomputerprogramsitself.Asaprogrammermyself,Ijustcan'timaginehowthiswouldwork.Whileit'struethataprogramcanaccumulatedataandmodifythewayitworksbasedonthecollecteddata,thisisnotthesamethingaswritinganewprogram.Ifsomeoneeverwritesthisprogramthatcanwriteanynewneededprogram,therewillbeahugenumberofcomputerprogrammersputoutofworkforever.
Thentherearethekindsoferrorsthatcomputersmakeversusthekindthatpeoplemake.Ifacomputergetsstuckinaloop,itappearstohavestoppedcompletely.Haveyoueverseenapersonwalkingdownthestreetsuddenlystopworking?Allfunctionsjustcease.Thepersonwouldjustfalldownuntilsomehowhiscomputerre-booted.Peopledocollapsefromtimetotime,butitisusuallybecausesomeotherpartbroke,likehavingaheartattack,andyoucanseethepersonrecognizethepainasittakesthemdown.Butifthehumancomputergotstuckinaloop,therewouldbeaninstantlossofconsciousnessandthebodywouldjustfallcompletelylimpwithnostruggle.Ihaveneverseenthat,butifthebrainoperatedjustlikeacomputer,youwouldexpecttoseeitonafairlyregularbasis.
Thenthereisthematterofspeed.Aswehaveseen,asimplecomputercandoabillionthingsinasecond.Whenitcomestothebrain,ithasnervesthathavesomesimilaritytothewiresincomputers.Nervescanalsocarryelectricityfromplacetoplace.Inacomputer,wirescomeoutofgatesandgointoothergates.Inthebrain,nervesareconnectedtogetherby"synapses."Thesesynapsesarespacesbetweennerveswheretheelectricityinonenervecreatesachemicalreaction,whichthencausesthenextnervetocreateitsownelectricity.Thesechemicalreactionsarepainfullyslow.
Noonehasshownthatthesenervesareconnectedupanythinglikethewiresinacomputer,buttheirlackofspeedmakesitveryunlikelythatitwoulddomuchgoodeveniftheconnectionsweresimilar.Aftertheelectricitytravelsquicklythroughthenervecell,itreachesthesynapse,wherethechemicalreactiontakesaboutonefivehundredthofasecondtocomplete.ThatmeansthatoursimplecomputerbuiltoutofNANDgatescoulddotwomillionthingsinthesametime
thatonlyonethingcouldbedonebyacomputerbuiltoutofnervesandsynapses.
Anotherareawherethedifferencebetweenthemindandcomputersisquiteobvious,isintheareaofrecognizingfaces.Themindisverygoodatit.Ifyouwalkintoapartywithfiftypeoplepresent,youwillknowinamatterofsecondswhetheryouareamongagroupoffriendsorofstrangers.Alotofresearchhasbeendoneintohowpeopleaccomplishthisfeat,andalotofveryinterestinginformationhasbeenuncovered.
Thereisalsoalotofspeculation,andtherearemanyfascinatingtheoriesabouttheunderlyingprinciplesandmechanisms.Butthecompleteandexactstructuresandfunctionshavenotbeenuncovered.
Ifyougiveacomputerapicturefileofaperson,andthengiveitthesamefileagain,itcancomparethetwofilesbytebybyteandseethateachbyteinonefileisexactlyequaltothecorrespondingbyteintheotherfile.Butifyougivethecomputertwopicturesofthesamepersonthatweretakenatdifferenttimes,orfromdifferentangles,orwithdifferentlighting,oratdifferentages,thenthebytesofthetwofileswillnotmatchupbytebybyte.Forthecomputertodeterminethatthesetwofilesrepresentthesamepersonisahugetask.Ithastorunverycomplexprogramsthatperformadvancedmathematicalfunctionsonthefilestofindpatternsinthem,thenfigureoutwhatthosepatternsmightlooklikefromdifferentangles,thencomparethosethingstoeveryotherfaceithaseverstoredonitsdisk,picktheclosestmatch,thendetermineifit'scloseenoughtobethepersonorjustsomeonethatlookssimilar.
Thepointisthatcomputershaveamethodofdealingwithpicturesbasedontheprinciplesonwhichcomputerswork.Usingtheseprinciplesalonehasnotyetyieldedcomputersorsoftwarethatcanrecognizeafacewithanywherenearthespeedandaccuracyofanyordinaryperson.
Voicerecognitionbycomputersisanothertechnologythathascomealongway,buthasmuchfurthertogotorivalwhattheminddoeseasily.
Soincomparingacomputertoabrain,itjustdoesn'tlookverylikelythattheyoperateonthesameprinciples.Thebrainisveryslow,thereisn'tanyplacetogetthesoftwaretorunit,andwedon'tseethetypesofproblemswewouldexpectwithcomputersoftwareerrors.
Incomparingacomputertothemind,thecomputerisvastlybetteratmath,but
themindisbetteratdealingwithfacesandvoices,andcancontemplatetheentiretyofsomeentitythatithaspreviouslyexperienced.
Sciencefictionbooksandmoviesarefullofmachinesthatreadmindsorimplantideasintothem,spaceshipswithbuilt-intalkingcomputersandlifelikerobotsandandroids.Thesemachineshavevaryingcapabilitiesandsomeoftheplotsdealwiththerobotwrestlingwithconsciousness,self-realization,emotions,etc.Thesemachinesseemtofeellessthancompletebecausetheyarejustmachines,andwantdesperatelytobecomefullyhuman.It'ssortofagrown-upversionofthechildren'sclassic"Pinocchio,"thestoryaboutamarionettewhowantstobecomearealboy.
Butwoulditbepossibletobuildsuchmachineswithavastlyexpandedversionofthetechnologythatweusedtobuildoursimplecomputer?
Optimismisagreatthing,anditshouldnotbesquashed,butaproblemwillnotbesusceptibletosolutionifyouareusingamethodologyortechnologythatdoesn'tmeasureuptothatproblem.Inthefieldofmedicine,somediseaseshavebeenwipedoutbyantibiotics,otherscanbepreventedbyinoculations,butothersstillplaguehumanitydespitethebestofcareanddecadesofresearch.Andlet'snotevenlookintosubjectslikepolitics.Maybemoretimeisallthat'sneeded,butyoualsohavetolookatthepossibilitythattheseproblemseitherareunsolvable,orthattheresearchhasbeenlookinginthewrongplacesfortheanswer.
Asanexample,manyvisionsofthefuturehaveincludedpeopletravelingaroundinflyingcars.Actually,severaltypesofflyingcarshavebeenbuilt.Buttheyareexpensive,inefficient,noisyandverydangerous.Theyworkonthesamebasicprinciplesashelicopters.Iftwoflyingcarshaveanysortofaminoraccident,everyonewilldiewhenbothcarscrashtotheEarth.Sotoday'saviationtechnologyjustwon'tresultinasatisfactoryflyingcar.Unlessanduntilsomeoneinventsacheapandreliableanti-gravitydevice,therewillnotbeamassmarketforflyingcarsandtrafficontheroadswillnotberelieved.
Ifyouwanttobuildamachinethatworksjustlikeaperson,certainlythebestwaytodoitwouldbetofindouthowthepersonworksandthenbuildamachinethatworksonthesameprinciples,haspartsthatdothesamethings,andiswiredupinthesamewayasaperson.
WhenThomasEdisoninventedthephonograph,hewasdealingwiththesubjectofsound.Soundisavibrationoftheair.Soheinventedanapparatusthatcapturedthevibrationsintheairandtransformedthemintoavibratinggroove
onthesurfaceofawaxcylinder.Thesoundcouldthenberecreatedbytransferringthevibrationsinthegroovebackintotheair.Thepointis,thatinordertorecreatesound,hefoundouthowsoundworked,andthenmadeamachinethatworkedonthesameprinciple.Soundisavibration,thegrooveinaphonographisavibration.
Alotofresearchhasbeendoneonthesubjectofwhatmakespeopletick.Alotofresearchhasbeendoneonthesubjectofhowtomakecomputersdothethingsthatpeopledo.Alotofthingshavebeendiscoveredandalotofthingshavebeeninvented.Idonotwanttominimizeanyoftheworkdone,orresultsachievedintheseareas.
Buttherearemanythingsthathavenotyetbeendiscoveredorinvented.
Manydeadbrainshavebeendissectedandtheirpartshavebeenstudiedandclassified.Thebraindoescontainnervecellswhichmoveelectricityfromoneplacetoanother.Thisisasimilaritybetweenbrainsandcomputers.Butresearchintotheactualoperationoflivinghumanbrainsisnecessarilylimited.Mostobservationshavebeenmadeduringsurgeriesthatwerenecessitatedbyaccidentordisease.Manyobservationshavebeenmadeofchangestobehaviorafteraninjuryordiseasehasdisabledcertainpartsofthebrain.Fromthisresearch,ithasbeenpossibletoassociatecertainfunctionswithcertainareasofthebrain.
Butnoonehasdiscoveredabus,aclock,anyregisters,anALUorRAM.Theexactmechanismofmemoryinthebrainremainsamystery.Ithasbeenshownthatnervesgrownewconnectionsovertime,anditisassumedthatthisisthemechanismoflearning,butnoonehasbeenabletosaythatthisparticularnervedoesthisexactfunction,aswecandowiththeindividualwiresinacomputer.
Everythingthatgoesintoacomputergetsturnedintoonecodeoranother.ThekeyboardgeneratesonebyteofASCIIperkeystroke,amicrophonegenerates44,100binarynumberspersecond,acolorcamerageneratesthreebinarynumbersperpixel,30timesasecond,andsoon.NoonehasisolatedtheuseofanycodeslikeASCII,binarynumbers,fontsoraninstructioncodeinthebrain.Theymaybethere,buttheyhavenotbeenisolated.Noonehastracedathoughtorlocatedamemoryinthesamewaythatwecouldfollowtheoperationofaprograminacomputer.
Itiswidelyassumedthatthebrainworksinsomemuchmorespreadoutwaythanasinglecomputer,thattherearethousandsorbillionsofcomputerelementsthatcooperateandsharethework.Butsuchelementshavenotyetbeenlocated.Intheworldofcomputing,thisideaiscalled'parallelprocessing'andcomputers
withdozensorhundredsofCPUshavebeenbuilt.Butthesecomputersstillhaven'tresultedinahumansubstitute.
Thinkofitallasapuzzle.Howpeopleworkisonesideofthepuzzle.Makingcomputersdothingsthatpeopledoistheothersideofthepuzzle.Piecesofthepuzzlearebeingassembledonbothsides.Theproblemisthatasprogressisbeingmadeonbothsides,itlooksmoreandmorelikethesearetwodifferentpuzzles,theyarenotcomingtogetherinthemiddle.Theyarenotconvergingintoasinglepicture.
Theresearchersareveryawareofthesedevelopments.Butwhenitcomestopopculture,peoplehearaboutnewinventionsallthetime,andseethefutureportrayedinsciencefictionfilms,andthelogicalconclusionseemstobethatresearchwillcontinuetosolvetheproblemsonebyoneuntilin10or20or30yearswewillhaveourelectro-mechanicalfriends.Inthepastcenturyweconqueredelectricity,flight,spacetravel,chemistry,nuclearenergy,etc.Sowhynotthebrainand/ormind?Theresearch,however,isstillatthestagewhereeverytimeonenewanswerisfound,itcreatesmorethanonemorenewquestion.
Soitappearsthatwhicheverwaywelookatit,neitherthebrainnorthemindworkonthesameprinciplesascomputersasweknowthem.Isay'asweknowthem'becausesomeothertypeofcomputermaybeinventedinthefuture.Butallofthecomputerswehavetodaycomeunderthedefinitionof'StoredProgramDigitalComputers,'andalloftheprinciplesonwhichtheyoperatehavebeenpresentedinthisbook.
Still,noneofthis'proves'thatasynthetichumancouldneverbebuilt,itonlymeansthatthecomputerprinciplesaspresentedinthisbookarenotsufficientforthejob.Somecompletelydifferenttypeofdevicethatoperatesonsomecompletelydifferentsetofprinciplesmightbeabletodoit.Butwecan'tcommentonsuchadeviceuntilsomeoneinventsone.
Goingbacktoasimplerquestion,doyourememberJoeandtheThermosbottle?HethoughtthattheThermoshadsomekindofatemperaturesensor,andaheaterandcoolerinside.Butevenifithadhadallofthatmachineryinit,itstillwouldn't"know"whattodo,itwouldjustbeamechanicaldevicethatturnedontheheaterorcoolerdependingonthetemperatureofthebeverageplacedinit.
Apairofscissorsisadevicethatperformsafunctionwhenmadetodoso.Youputafingerandthumbintheholesandsqueeze.Thebladesattheotherendofthescissorsmovetogetherandcutsomepaperorclothorwhateveritisthatyou
haveplacedintheirway.Dothescissors"know"howtocutshapesoutofpaperorhowtomakeadressoutofcloth?Ofcoursenot,theyjustdowhatthey'retold.
Similarly,NANDgatesdon't"know"whattheyaredoing,theyjustreacttotheelectricityorlackofitplacedontheirinputs.Ifonegatedoesn'tknowanything,thenitdoesn'tmatterhowmanyofthemyouconnecttogether,ifoneofthemknowsabsolutelyzero,amillionofthemwillalsoknowzero.
Weusealotofwordsthatgivehumancharacteristicstoourcomputers.Wesaythatit"knows"things.Wesayit"remembers"things.Wesaythatit"sees,"and"understands."Evensomethingassimpleasadeviceadapter"listens"foritsaddresstoappearontheI/Obus,orajumpinstruction"decides"whattodo.Thereisnothingwrongwiththisaslongasweknowthetruthofthematter.
Nowthatweknowwhatisinacomputer,andhowitworks,Ithinkitisfairlyobviousthattheanswertothequestion"ButHowdoitKnow?"issimply"Itdoesn'tknowanything!"
Index