The secret life of programs jon steinhart - Download the full set of chapters carefully compiled

Page 1


The secret life of programs Jon Steinhart

Visit to download the full and correct content document: https://textbookfull.com/product/the-secret-life-of-programs-jon-steinhart/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

The Secret Life of Programs Understand Computers Craft Better Code 1st Edition Jonathan E. Steinhart

https://textbookfull.com/product/the-secret-life-of-programsunderstand-computers-craft-better-code-1st-edition-jonathan-esteinhart/

The Alter Ego Effect: The Power of Secret Identities to Transform Your Life Todd Herman

https://textbookfull.com/product/the-alter-ego-effect-the-powerof-secret-identities-to-transform-your-life-todd-herman/

20 years in the secret service my life with five presidents Second Edition Youngblood

https://textbookfull.com/product/20-years-in-the-secret-servicemy-life-with-five-presidents-second-edition-youngblood/

Emotional Intelligence The Top Secret to Using Emotional Intelligence to Get the Most Out of Your Life

https://textbookfull.com/product/emotional-intelligence-the-topsecret-to-using-emotional-intelligence-to-get-the-most-out-ofyour-life-naomi-mccullough/

Hannah Arendt The Promise of Education Jon Nixon

https://textbookfull.com/product/hannah-arendt-the-promise-ofeducation-jon-nixon/

Day Of The Delphi 1st Edition Jon Land

https://textbookfull.com/product/day-of-the-delphi-1st-editionjon-land/

The Python Book Jon White

https://textbookfull.com/product/the-python-book-jon-white/

The Secret Diary of Hendrik Groen Groen

https://textbookfull.com/product/the-secret-diary-of-hendrikgroen-groen/

The Secret Ingredient: Recipes for Success in Business and Life First Howard Books Hardcover Edition Gigi Butler

https://textbookfull.com/product/the-secret-ingredient-recipesfor-success-in-business-and-life-first-howard-books-hardcoveredition-gigi-butler/

THE SECRET LIFE OF PROGRAMS

Understand Computers Craft Better Code

SanFrancisco

THE SECRET LIFE OF PROGRAMS. Copyright©2019byJonathanE.Steinhart.

Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorbyany means,electronicormechanical,includingphotocopying,recording,orbyanyinformationstorage orretrievalsystem,withoutthepriorwrittenpermissionofthecopyrightownerandthepublisher.

ISBN-10:1-59327-970-1

ISBN-13:978-1-59327-970-7

Publisher:WilliamPollock

ProductionEditor:JanelleLudowise

CoverIllustration:JoshEllingson

InteriorDesign:OctopodStudios

DevelopmentalEditors:CorbinCollinsandAnnieChoi

TechnicalReviewer:AubreyAnderson

Copyeditor:RachelMonaghan

Compositor:HappenstanceType-O-Rama

Proofreader:PaulaL.Fleming

Indexer:JoAnneBurek

Thefollowingimagesareattributedasfollows:CompositioninFigure6-36courtesyofHanalei Steinhart.BrickwallinFigures11-3,11-4,11-7and11-8from www.cadhatch.com Figure1425from The Rocky Horror Picture Show (1975).

Forinformationondistribution,translations,orbulksales,pleasecontactNoStarchPress,Inc. directly:

NoStarchPress,Inc.

2458thStreet,SanFrancisco,CA94103

phone:1.415.863.9900;info@nostarch.com www.nostarch.com

Library of Congress Cataloging-in-Publication Data

Names:Steinhart,JonathanE.,author.

Title:TheSecretLifeofPrograms/JonathanE.Steinhart.

Description:SanFrancisco:NoStarchPress,Inc.,[2019]

Identifiers:LCCN2019018295(print)|LCCN2019021631(ebook)|ISBN 9781593279714(epub)|ISBN159327971X(epub)|ISBN9781593279707(print) |ISBN1593279701(print)

Subjects:LCSH:Computerprogramming.|Programminglanguages(Electronic computers)|Browsers(Computerprograms)

Classification:LCCQA76.6(ebook)|LCCQA76.6.S7352019(print)|DDC 005.1 dc23

LCrecordavailableathttps://lccn.loc.gov/2019018295

NoStarchPressandtheNoStarchPresslogoareregisteredtrademarksofNoStarchPress,Inc. Otherproductandcompanynamesmentionedhereinmaybethetrademarksoftheirrespective owners.Ratherthanuseatrademarksymbolwitheveryoccurrenceofatrademarkedname,weare usingthenamesonlyinaneditorialfashionandtothebenefitofthetrademarkowner,withno intentionofinfringementofthetrademark.

Theinformationinthisbookisdistributedonan“AsIs”basis,withoutwarranty.Whileevery precautionhasbeentakeninthepreparationofthiswork,neithertheauthornorNoStarchPress, Inc.shallhaveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedor allegedtobecauseddirectlyorindirectlybytheinformationcontainedinit.

ACKNOWLEDGMENTS

Therearealotofinfluencesthatcontributedtomakingthisbookpossible.Thatstartswithmy parentsRobertandRosalynSteinhartformakingmepossibleandthenencouragingmyinterestin science,atleastuptothepointatwhichitstartedtoscarethem.Manyawesometeacherstookit fromthereincludingBeatriceSeagal,WilliamMulvahill,andMillerBugliari.MuchthankstoPaul RubenfieldfortellingmeaboutbothCivilDefenseandtheBellLabsExplorerScoutpost. It’simpossibletogiveenoughcredittomyExplorerScoutadvisorsCarlChristiansenandHeinz Lycklama.Theychangedmylife.ThroughthemImetmanyamazingpeopleatBellTelephone LaboratoriesincludingJoeCondon,SandyFraser,DaveHagelbarger,DickHause,JimKaiser,Hank McDonald,MaxMathews,DennisRitchie,KenThompson,andDaveWeller.Ilearnedalotfromeach ofthem.

ThankstoAubreyAnderson,ClemCole,LeeJalovec,A.C.Mendiones,EdPost,andBetsyZellerfor makingitthroughthewholethingatleastonce.AndespeciallytoAubreyfortechnicalediting. ThanksalsotoMattBlaze,AdamCecchetti,SandyClark,TomDuff,NatalieFreed,FrankHeidt,DV Henkel-Wallace(a.k.aGumby),LouKatz,Sara-JayeTerp,Talin,andPaulVixieforproviding feedbackonparticularchapters.

AndthankstoallofthepeoplewhoansweredthephonewhenIcalledwithgeneralquestions includingWardCunningham,JohnGilmore,EvelynMast,MikePerry,AlexPolvi,AlanWirfs-Brock, andMikeZuhl.Andofcourse,RakelHellberg,thegirlontheskilift,forprovidingoneofthenudges thatmotivatedmefinishthisproject.

Thisbookwouldnothavebeenpossiblewithoutthesupportandencouragementofpeoplein variousgeekcommunitiesincludingAMW,Hackers,andTUHS.

ThankstoHanaleiSteinhartforthecompositioninFigure6-36andtoJulieDonnellyforthescarf inFigure11-41

ThankstoTonyCatforallowingmetousehisimageandforkeepingmykeyboardfulloffur.

PREFACE

Iwasbornageek.Accordingtomyfather,Iusedanimaginaryswitchtoturnontheswingsbefore usingthem,andIwouldturnthemoffwhenIwasdone.Machineryjustspoketomeaboutitsinner workings.IresembledC-3POunderstanding“thebinarylanguageofmoisturevaporators.”Iwas fortunatetogrowupinatimeinwhichonecouldexaminetheworkingsofmostthingswithouta microscope.

Inhindsight,IhadaverysurrealchildhoodgrowingupinNewJersey.Itinkeredwitheverything, oftentothedetrimentofmymom’snervoussystem.Myparentsgavemelotsof“50-in-one”project kitsbutbecameuncomfortablewhenIstartedhookingthemtogetherforprojectsthatweren’tin thebooks.ThisculminatedwiththePillowBurglarAlarm,whichcaughtthetoothfairyinaction a pooreconomicchoicethatwasneverthelessemotionallysatisfying.Icollectedbrokentelevisions andotherappliancesthatpeoplewouldleaveoutongarbagedaysothatIcouldtakethemapart, learnhowtheyworked,andbuildthingsoutoftheparts.Oneofmyfavoritetoyswasmydad’s 1929ErectorSet.Thespaceprogrammadeitagreattimetobeinterestedtechnology;Iremember standinginourfrontyardwithmyfatheronenightwatchingEcho1flyover. Mostkidshadpaperroutes;Irepairedtelevisionsandstereos.MyfatherworkedforIBM,andI occasionallywentwithhimtoworkandwasawedbythebigcomputers.Hetookmewithhimto theElectroShowinAtlanticCitywhenIwaseight,andIrememberplayingwithanIBM1620.Ialso rememberbeingfascinatedbytheequipmentattheTektronixbooth,whichmayhaveinfluenced mylaterchoicetoworkforthem.AyearlaterIwenttotheWorld’sFairinNewYorkandwasawed bytheBellSystemexhibit;bychanceIlaterworkedwithoneofitsdesigners.

Ireceivedanamazingpost-Sputnikpublicschooleducation,thelikesofwhichnolongerexistsin America.Wepassedaroundthejugofmercuryinfifthgrade.Iblewupthechemistrylabinsixth gradeandlearnedfromtheexperienceinsteadofbeinglockedaway.(Icanstillquotetherecipefor makingnitrogentriiodide.)Iremembermyeighth-gradescienceteachermarchingusoutofthe classroomandtakingusintoNewYorkCitytoseethemovie 2001: A Space Odyssey becausehe thoughtthatitwasimportant.Hedidthiswithnoparentalnotesorpermissionsslips;ateacher whodidthattodaywouldlikelylosetheirjob,orworse.Wemadegunpowderinhighschool chemistry,shotrocketsateachotheronthefootballfieldinphysicsclass,lancedourownfingersto dobloodtypinginbiology.Afarcryfromtodaywhensomanymillionsaredrowninginfive-gallon bucketsthatwarningsarerequired,wetfloorsstrikefearintotheheartsofman,andgovernment officialsaredismissiveofscienceandunabletodistinguishtinkeringfromterrorism. Outsideofschool,myparentssignedmeupfortheBoyScouts,whichIloved,andLittleLeague, whichIhated.Scoutingtaughtmealotaboutthephysicalworldfromhorsebackridingtosafely playingwithfiretooutdoorsurvival.LittleLeaguetaughtmethatIdidn’tliketeamsports. Hamradiowasbiginthosedays;itwaswheretinkeringhappened.IvolunteeredforthelocalCivil DefenseemergencyradiocommunicationsgroupjustsoIcouldplaywiththeequipment.Theyhad

aprimitiveradioteletypesystem,whichIredesignedandendedupbuildingunitsforother municipalities.Ilovedthethree-dimensionalmechanicalcontraptionthatwasaTeletype. WhenIwasinhighschool,afriendtoldmeaboutanExplorerScoutpostthatmeteveryMonday eveningatBellTelephoneLaboratoriesinnearbyMurrayHill.Ijoinedandgottoplaywith computersbackwhentheywerethesizeoflargehouses.Iwashooked.Itwasn’tlongbeforeIwas leavingschoolearly,hitchhikinguptotheLabs,andtalkingpeopleintolettingmein.Thisturned intoaseriesofamazingsummerjobsworkingwithincrediblepeoplethatchangedmylife.Ilearned alotjustbypokingmyheadintopeople’slabsandaskingthemwhattheyweredoing.Iendedup writingsoftwareforthemeventhoughIplannedtostudyelectricalengineering,becausehardware projectsjustcouldn’tbefinishedinasummer.

Ifeltthatthebestwaytohonormyscoutadvisorswastofollowintheirfootstepsbytryingtohelp newergenerationsofbuddingyoungtechnologistsalongtheirpathonceIwasinapositiontodo so.Thisturnedouttobedifficult,astheheydayofAmericanresearchhasgivenwaytoincreasing shareholdervalue;productsthemselvesarenotvaluedashighlyastheprofitstheygenerate,which makesresearchhardtojustify.Companiesrarelyletkidsrunwildontheirpremisesanymore,for liabilityreasons.IhadoriginallythoughtIwouldworkthroughscouting,butrealizedIcouldn’t becausescoutinghadadoptedsomepolicesthatIcouldn’tsupport,asIhadnevergottenmysexual discriminationmeritbadge.Instead,Ivolunteeredinmylocalschoolsystem.

IstartedwritingthisbooktosupplementaclassthatIvolunteeredtoteach.Ididthisbeforethe internetwasasreadilyaccessibleasitistoday.Icurrentlyliveinafairlypoorruralfarming community,sotheoriginaldraftofthisbooktriedtobeall-inclusiveundertheassumptionthat studentswouldn’tbeabletoaffordsupplementarymaterials.Thatturnedouttobeanimpossible task.

Lotsofmaterialaboutdifferentprogramminglanguagesandconceptsisnowavailableonline,and mostpeoplehaveinternetaccessathomeorattheirschoolorlibrary.I’verewrittenthematerial withtheexpectationthatreaderscannowmuchmoreeasilyfindadditionalinformationonline.So, ifsomethingisn’tclearoryouwantmoreinformation,lookitup.

Recently,anumberofstudentsIknowhaveexpressedfrustrationwiththewaythey’rebeing taughtprogramming.Althoughtheycanfindinformationonline,theykeepaskingwheretheycan findeverythingtheyneedinoneplace.Thisbookiswrittentobethatresource.

Iwasluckytogrowupcontemporaneouslywithcomputers.Wedevelopedtogether.Ihaveahard timeimaginingwhatitmustbeliketojumpintothematurefieldthatcomputingistodaywithout havingthebackground.Themostchallengingpartsofwritingthisbookweredecidinghowfarto reachbackintothepastforexamplesandchoosingelementsofmoderntechnologytodiscuss.I settledonsortofaretrofeel,asonecanlearnmostofwhat’snecessaryfromolder,simpler technologythat’seasiertounderstand.Newer,morecomplextechnologiesarebuiltusingthesame buildingblocksastheolderones;knowingthoseblocksmakesunderstandingnewtechnologies mucheasier.

It’sadifferentagenow.Gadgetsaremuchhardertotakeapart,repair,andmodify.Companiesare abusinglawssuchastheDigitalMillenniumCopyrightAct(DMCA)topreventpeoplefrom repairingdevicestheyown,whichisfortunatelyresultingin“righttorepair”lawsinsomeplaces. AsAmericans,wegetmixedmessagesfromourgovernment;ontheonehandwe’reencouragedto gointoSTEMcareers,whileontheotherhandweseesciencedenigratedandSTEMjobs outsourced.It’snotclearthattheUSwouldhaveeverbecomeatechnologypowerhouseifthis environmenthadexistedahalf-centuryago.

Thenagain,therearebrightspots.Makerspacesareproliferating.Somekidsarebeingallowedto buildthingsandarediscoveringthatit’sfun.Electronicpartsarecheaperthanthey’veeverbeen,as longasyoudon’twantoneswithwiresonthem.Smartphoneshavemoreprocessingpowerthanall

thecomputersintheworldcombinedwhenIwasakid.Computersarecheaperthananybodyever imagined;smallcomputerssuchastheRaspberryPiandArduinocostlessthanapizzaandhavea hugevarietyofavailabletoppings. Withsuchpoweravailable,it’stemptingtojustplaywiththehigh-levelfunctionality.It’slike playingwithLEGO.MyparentsgavemeoneofthefirstLEGOsetsmade;itprettymuchjusthad rectangularblocks.ButIhadmyimaginationandIcouldbuildanythingIwanted.Today,youcan geta Star Wars LEGOsetanddeployaprefabricatedYoda.It’smuchhardertoinventnew characters.Thefancypieceshampertheimagination.

There’sagreatsceneintheclassic1939movie The Wizard of Oz inwhichthewizardisexposedand bellows,“Paynoattentiontothatmanbehindthecurtain.”Thisbookisforthoseofyouwhoaren’t goingtolistentothatandwanttoknowwhat’sbehindthecurtain.Myintentistoshinelightonthe fundamentalbuildingblocksonwhichhigh-levelfunctionalityisbuilt.Thisbookisforthosewhose imaginationisn’tsatisfiedbyhigh-levelfunctionalityalone;it’sforthosewhoaredrawnto creating new high-levelfunctionality.Ifyou’reinterestedinbecomingawizardinadditiontobeing amerewielderofmagicitems,thenthisbookisforyou.

INTRODUCTION

Afewyearsago,IwasridingonaskiliftwithourSwedishexchangestudent.Iaskedherifshehad thoughtaboutwhatshewasgoingtodoafterhighschool.Shesaidthatshewasconsidering engineeringandhadtakenaprogrammingclassthepreviousyear.Iaskedherwhattheytaught. Shereplied,“Java.”Iinstinctivelyrespondedwith“That’stoobad.”

WhydidIsaythat?Tookmeawhiletofigureitout.It’snotthatJavaisabadprogramming language;it’sactuallyprettydecent.IsaiditbecauseofthewayinwhichJava(andotherlanguages) aretypicallyusedtoteachprogrammingtoday without teaching anything about computers.Ifthis strikesyouasabitodd,thenthisbookisforyou.

TheJavaprogramminglanguagewasinventedbyJamesGosling,MikeSheridan,andPatrick Naughtoninthe1990satSunMicrosystems.ItwasmodeledinpartaftertheCprogramming language,whichwaswidelyusedatthetime.Cdoesn’tincludeautomaticmanagementofmemory, andmemorymanagementerrorswereacommonheadacheatthetime.Javaeliminatedthatclassof programmingerrorsbydesign;ithidtheunderlyingmemorymanagementfromtheprogrammer. That’spartofwhatmakesitsuchagoodprogramminglanguageforbeginners.Butittakesmuch morethanagoodprogramminglanguagetoproducegoodprogrammersandprograms.Andit turnedoutthatJavaintroducedawholenewclassofharder-to-debugprogrammingproblems, includingpoorperformanceresultingfromthehiddenmemorymanagementsystem.

Asyou’llseeinthisbook,understandingmemoryisakeyskillforprogrammers.Whenyou’re learningtoprogram,it’seasytodevelophabitsthatbecomehardtobreak.Studieshaveshownthat childrenwhogrewupplayingatso-called“safe”playgroundshaveahigherrateofinjurieslaterin lifethanthosewhodidn’t,presumablybecausetheydidn’tlearnthatfallinghurts.Programmingis ananalogoussituation.Safeprogrammingenvironmentsmakegettingstartedlessscary,butyou alsoneedtopreparefortheoutsideworld.Thisbookhelpsyoumakethattransition.

WHY GOOD PROGRAMMING IS IMPORTANT

Tounderstandwhyit’sproblematictoteachcomputerprogrammingwithoutalsoteachingabout computers,firstconsiderhowubiquitouscomputershavebecome.Thepriceofcomputershas fallensodramaticallythatusingthemisnowthecheapestwaytobuildmanythings.Forexample, usingacomputertodisplayanimageofanold-fashionedanalogclockonacardashboardcosts muchlessthanamechanicalclock.Thisisaresultofhowcomputerchipsaremanufactured;they’re moreorlessprinted.It’snolongerabigdealtostampoutachipthatcontainsbillionsof components.NotethatI’mtalkingaboutthepriceofcomputersthemselves,notthepriceofthings thatcontaincomputers.Ingeneral,acomputerchiptodaycostslessthanthepackaginginwhichit’s shipped.Computerchipsareavailablethatcostpennies.Therewilllikelycomeatimewhenitwill bedifficulttofindanythingthatdoesn’tcontainacomputer.

Lotsofcomputersdoinglotsofthingsmeanslotsofcomputerprograms.Becausecomputersareso ubiquitous,thefieldofcomputerprogrammingisincrediblydiverse.Asinmedicine,many

programmersbecomespecialists.Youcanspecializeinareassuchasvision,animation,webpages, phoneapps,industrialcontrol,medicaldevices,andmore.

Butthestrangethingaboutcomputerprogrammingisthatunlikeinmedicine,inprogrammingyou canbecomeaspecialistwithouteverbeingageneralist.Youprobablywouldn’twantaheart surgeonwhoneverlearnedanatomy,buttheequivalenthasbecomenormalformany programmerstoday.Isthisreallyaproblem?Infact,there’splentyofevidencethatthisisn’t workingverywell,withalmostdailyreportsofsecuritybreachesandproductrecalls.Therehave beencourtcasesinwhichpeopleconvictedofdrunkdrivingbybreathalyzerhavewontherightto havethebreathalyzercodereviewed.Itturnedoutthatthecodewasfullofbugs,whichresultedin overturnedconvictions.Recently,apieceofantivirussoftwarecrashedapieceofmedical equipmentinthemiddleofaheartsurgery.LiveswerelostduetodesignissuesintheBoeing737 MAXairplane.Thelargenumberofincidentslikethesedon’tinspirealotofconfidence.

LEARNING TO CODE IS ONLY A STARTING PLACE

Partofthereasonforthisstateofaffairsisthatit’snotallthatdifficulttowritecomputerprograms that appear towork,orworkmuchofthetime.Let’susethechangesinmusic(notdisco!)inthe 1980sasananalogy.Peopleusedtohavetodevelopafoundationinordertomakemusic.This includedlearningmusictheory,composition,andhowtoplayaninstrument;eartraining;andlots ofpracticing.ThentheMusicalInstrumentDigitalInterface(MIDI)standard,originallyproposedby IkutaroKakehashiofRoland,camealong,whichletanyonemake“music”fromtheircomputer withouteverhavingtodevelopcalluses.It’smyopinionthatonlyasmallpercentageofcomputergenerated“music”isactuallymusic;it’smostlynoise. Music isproducedbyactualmusicians who mayormaynotuseMIDItobuildontheirfoundation.Programmingthesedayshasbecomealot likeusingMIDI.Younolongerhavetosweatmuchorspendyearspracticingorevenlearntheoryin ordertowriteprograms.Butthatdoesn’tmeanthesearegoodorreliableprograms. Thissituationislikelytogetworse,atleastintheUnitedStates.Wealthypeoplewithvested interests,likethosewhoownsoftwarecompanies,havebeenlobbyingforlegislationmandating thateverybodylearntocodeinschool.Thissoundsgreatintheory,butit’snotagreatideain practicebecausenoteverybodyhastheaptitudetobecomeagoodprogrammer.Wedon’tmandate thateverybodylearntoplayfootballbecauseweknowthatit’snotforeverybody.Thelikelygoalof thisinitiativeisnottoproducegreatprogrammersbutrathertoincreasesoftwarecompanyprofits byfloodingthemarketwithlargenumbersofpoorprogrammers,whichwilldrivedownwages. Thepeoplebehindthispushdon’tcareverymuchaboutcodequality theyalsopushfor legislationthatlimitstheirliabilityfordefectiveproducts.Ofcourse,youcanprogramforfunjust likeyoucanplayfootballforfun.Justdon’texpecttobedraftedfortheSuperBowl.

In2014,PresidentObamasaidthathehadlearnedtocode.Hediddragafewthingsaroundinthe excellentvisualprogrammingtoolBlockly,andheeventypedinonelineofcodeinJavaScript(a programminglanguageunrelatedtoJava,whichwasinventedatNetscape,thepredecessortothe MozillaFoundationthatmaintainsnumeroussoftwarepackages,includingthe Firefox web browser.)Now,doyouthinkthatheactuallylearnedtocode?Here’sahint:ifyoudo,youshould probablyworkonhoningyourcriticalthinkingskillsinadditiontoreadingthisbook.Sure,hemay havelearnedateensybitaboutprogramming,but no, he didn’t learn to code.Ifhecouldlearnto codeinanhour,thenitfollowsthatcodingissotrivialthattherewouldn’tbeaneedtoteachitin schools.

IMPORTANCE OF LOW-LEVEL KNOWLEDGE

Aninterestingandsomewhatcontraryviewabouthowtoteachprogrammingwasexpressedina blogposttitled“HowtoTeachComputationalThinking”byStephenWolfram,thecreatorof MathematicaandtheWolframlanguage.Wolframdefinescomputationalthinkingas“formulating thingswithenoughclarity,andinasystematicenoughway,thatonecantellacomputerhowtodo them.”Icompletelyagreewiththisdefinition.Infact,it’sinlargepartmymotivationforwriting thisbook.

ButIstronglydisagreewithWolfram’spositionthatthoselearningtoprogramshoulddevelop computationalthinkingskillsusingpowerfulhigh-leveltools,suchasthosethathe’sdeveloped, insteadoflearningtheunderlyingfoundationaltechnologies.Forexample,it’sclearfromtherising interestinstatisticsovercalculusthat“datawrangling”isagrowingfield.Butwhathappenswhen peoplejustfeedgiantpilesofdataintofancyprogramsthatthosesamepeopledon’tintimately understand?

Onepossibilityisthattheygenerateinteresting-lookingbutmeaninglessorincorrectresults.For example,arecentstudy(“GeneNameErrorsAreWidespreadintheScientificLiterature”byMark Ziemann,YotamEren,andAssamEl-Osta)showedthatone-fifthofpublishedgeneticspapershave errorsduetoimproperspreadsheetusage.Justthinkofthekindsoferrorsandramificationsthat morepowerfultoolsinthehandsofmorepeoplecouldproduce!Gettingitrightiscrucialwhen people’slivesareaffected.

Understandingunderlyingtechnologieshelpsyoudevelopasenseofwhatcangowrong.Knowing justhigh-leveltoolsmakesiteasytoaskthewrongquestions.It’sworthlearningtouseahammer beforegraduatingtoanailgun.Anotherreasonforlearningunderlyingsystemsandtoolsisthatit givesyouthepowertobuildnewtools,whichisimportantbecausetherewillalwaysbeaneedfor toolbuilders,eveniftoolusersaremorecommon.Learningaboutcomputerssothatthebehavior ofprogramsisn’tamysteryenablesyoutocraftbettercode.

WHO SHOULD READ THIS BOOK?

Thisbookisforpeoplewhowanttobecomegoodprogrammers.Whatmakesagoodprogrammer? Firstandforemost,agoodprogrammerhasgoodcriticalthinkingandanalysisskills.Tosolve complexproblems,aprogrammerneedstheabilitytoevaluatewhetherornotprogramsactually solvetherightproblemcorrectly.Thisismoredifficultthanitsounds.It’snotuncommonforan experiencedprogrammertolookatsomeoneelse’sprogramandsnarkilycomment,“Why,that’sa complexnonsolutiontoasimplenonproblem.”

Youmaybefamiliarwithaclassicfantasytropeofwizardsacquiringpoweroverthingsbylearning theirtruenames.Andwoebetothewizardwhoforgetsadetail.Goodprogrammersarelikethese wizardswhocanholdtheessenceofthingsintheirmindswithoutdroppingdetails. Goodprogrammersalsohavesomedegreeofartistry,likeskilledcraftspeople.It’snotuncommon tofindcodethatiscompletelyincomprehensible,justlikemanyEnglishspeakersarebaffledby JamesJoyce’snovel Finnegans Wake.Goodprogrammerswritecodethatnotonlyworksbutisalso easyforotherstounderstandandmaintain. Finally,goodprogrammersneedadeepunderstandingofhowcomputerswork.Youcan’tsolve complexproblemswellusingashallowbaseofknowledge.Thisbookisforpeoplewhoarelearning programmingbutareunsatisfiedwiththelackofdepth.It’salsoforpeoplewhoarealready programmingbutwantmore.

WHAT ARE COMPUTERS?

Acommonansweristhatcomputersareappliancesthatpeopleusefortaskssuchaschecking email,shoppingonline,writingpapers,organizingphotos,andplayinggames.Thisdefinitionis partlytheresultofsloppyterminologythatbecamecommonplaceasconsumerproductsbeganto incorporatecomputers.Anothercommonansweristhatcomputersarethebrainsthatmakeour high-techtoys,suchascellphonesandmusicplayers,work.Thisisclosertothemark. Sendingemailandplayinggamesaremadepossiblebyprogramsrunningoncomputers.The computeritselfislikeanewbornbaby.Itdoesn’treallyknowhowtodomuch.Wehardlyeverthink aboutthebasicmachineryofhumanbeings,becausewemostlyinteractwiththepersonalitiesthat arerunningonthatbasicmachinery,justlikeprogramsrunningoncomputers.Forexample,when you’reonawebpage,you’renotreadingitusingjustthecomputeritself;you’rereadingitusing programssomeoneelsewrotethatarerunningonyourcomputer,thecomputerhostingtheweb page,andallofthecomputersinbetweenthatmaketheinternetfunction.

WHAT IS COMPUTER PROGRAMMING?

Teachersarepeoplewhotrainthebasichumanmachinerytoperformcertaintasks.Similarly, programmingisaboutbecomingateacherofcomputers.Programmersteachcomputerstodowhat theprogrammerswantthemtodo.

Knowinghowtoteachcomputersisuseful,especiallywhenyouwantacomputertodosomething thatitdoesn’tknowhowtodoandyoucan’tjustgobuyaprogramforitbecausenobodyhas createdoneyet.Forexample,youprobablytaketheWorldWideWebforgranted,butitwas inventednotlongago,whenSirTimBerners-LeeneededabetterwayforscientistsattheEuropean OrganizationforNuclearResearch(ConseilEuropéenpourlaRechercheNucléaire,orCERN)to shareinformation.Andhegotknightedforit.Howcoolisthat?

Teachingcomputersiscomplicated,butit’seasierthanteachingpeople.Weknowalotmoreabout howcomputerswork.Andcomputersarealotlesslikelytothrowuponyou.

Computerprogrammingisatwo-stepprocess:

1. Understandtheuniverse.

2. Explainittoathree-year-old.

Whatdoesthismean?Well,youcan’twritecomputerprogramstodothingsthatyouyourselfdon’t understand.Forexample,youcan’twriteaspellcheckerifyoudon’tknowtherulesforspelling,and youcan’twriteagoodactionvideogameifyoudon’tknowphysics.So,thefirststepinbecominga goodcomputerprogrammeristolearnasmuchasyoucanabouteverythingelse.Solutionsto problemsoftencomefromunexpectedplaces,sodon’tignoresomethingjustbecauseitdoesn’t seemimmediatelyrelevant.

Thesecondstepoftheprocessrequiresexplainingwhatyouknowtoamachinethathasavery rigidviewoftheworld,likeyoungchildrendo.Thisrigidityinchildrenisreallyobviouswhen they’reaboutthreeyearsold.Let’ssayyou’retryingtogetoutthedoor.Youaskyourchild,“Where areyourshoes?”Theresponse:“There.”She did answeryourquestion.Theproblemis,shedoesn’t understandthatyou’rereallyaskinghertoputhershoesonsothatyoubothcangosomewhere. Flexibilityandtheabilitytomakeinferencesareskillsthatchildrenlearnastheygrowup.But computersarelikePeterPan:theynevergrowup.

Computersarealsolikeyoungchildreninthattheydon’tknowhowtogeneralize.They’restill usefulbecauseonceyoufigureouthowtoexplainsomethingtothem,they’reveryfastandtireless aboutdoingit,thoughtheydon’thaveanycommonsense.Acomputerwilltirelesslydowhatyou askwithoutevaluatingwhetherit’sthewrongtask,muchliketheenchantedbroomsticksin“The

Sorcerer’sApprentice”segmentofthe1940movie Fantasia.Askingacomputertodosomethingis likeaskingthegeniefromamagiclantern(nottheFBIversion)tograntawish.Youhavetobe reallycarefulhowyouphraseit!

YoumaydoubtwhatI’msayingherebecausecomputersseemmorecapablethantheyare.When youuseacomputer,forexample,itknowshowtodrawpictures,correctyourspelling,understand whatyou’resaying,playmusic,andsoon.Butkeepinmind,that’snotthecomputer it’sa complicatedsetofcomputerprogramsthatsomeoneelsewrotethatallowsthecomputertodoall ofthosetasks.Computersareseparatefromtheprogramsthatrunonthem.

It’slikewatchingacarontheroad.Itseemsprettygoodatstoppingandstartingattherighttimes, avoidingobstacles,gettingwhereit’sgoing,eatingwhenitgetshungry,andsoon.Butit’snotjust thecar.It’sthecarandthedriverpackagedtogether.Computersarelikethecars,andprogramsare likethedrivers.Withoutknowledge,youcan’ttellwhat’sdonebythecarandwhat’sdonebythe driver.(See“SouthboundontheFreeway”byMaySwenson.Youmightchangeyouranswertothe questionposedattheendofthepoemduringyourlifetime.)

Insum,computerprogramminginvolveslearningwhatyouneedtoknowtosolveaproblemand thenexplainingittoayoungchild.Becausetherearelotsofwaystosolveaproblem,programming isjustasmuchanartasitisascience.Itinvolvesfindingelegantsolutionsasopposedto usingbruteforce.Yes,you can getoutofahousebybashingaholeinthewall,butit’sprobablyalot easiertogooutthedoor.Manycanwritesomethinglike HealthCare.gov inmillionsoflinesofcode, butittakesskilltodoitinthousandsoflines.

Beforeyoucaninstructathree-year-old,though,youneedtolearnaboutthree-year-oldsandwhat theyunderstand.Andthisisn’tanyordinarythree-year-old it’sanalienlifeform.Acomputer doesn’tplaybythesamerulesthatwedo.Youmayhaveheardofartificialintelligence(AI),which triestogetcomputerstoactmorelikepeople.Progressinthatfieldhasmovedmuchslowerthan originallyanticipated.That’smainlybecausewedon’treallyunderstandtheproblem;wedon’t knowenoughabouthowhumansthink.Asyoucanimagine,it’sprettyhardtoteachanaliento thinkaswedowhenweourselvesdon’tknowhowexactlyit’sdone.

Thehumanbrainletsyoudothingswithoutconsciouslythinkingaboutthem.Yourbrainstarted outasjustapieceofhardware,whichthengotprogrammed.Forexample,youlearnedtomove yourfingersandthenyoulearnedtograbthings.Afterpractice,youcanjustgrabthingswithout thinkingaboutallthestepsthatmakeitpossible.PhilosopherssuchasJeanPiaget(French psychologist,1898–1980)andNoamChomsky(Americanlinguistbornin1928)havedeveloped differenttheoriesabouthowthisprocessoflearningworks.Isthebrainjustageneralpieceof equipment,ordoesithavespecialhardwareforfunctionslikelanguage?Thisissueisstillbeing studied.

Ourincredibleabilitytoperformtasksunconsciouslymakeslearninghowtoprogramdifficult, becauseprogrammingrequiresbreakingdowntasksintosmallerstepsthatacomputercanfollow. Forexample,youprobablyknowhowtoplaytic-tac-toe.Getagroupofpeopletogetherandhave eachofyouindependentlylistthestepsaplayershouldtakeinordertomakeagoodmoveforany configurationoftheboard.(I’msureyoucanfindthisonline,butdon’tlookitup.)Aftereverybody hasmadetheirlists,holdaplayoff.Findoutwhoserulesrule!Howgoodwereyourrules?What sortofthingsdidyoumiss?Doyouactuallyknowwhatyou’redoingwhenyouplaythegame? Chancesare,therewereanumberoffactorsthatyoudidn’tthinktospelloutbecauseyou understandthemintuitively.

Incaseit’snotobvious,thefirststep,understandingtheuniverse,ismuchmoreimportantthanthe second,explainingittoathree-year-old.Thinkaboutit:whatgoodisittoknowhowtotalkifyou don’tknowwhattosay?Despitethis,currenteducationfocusesonthesecondstep.Thisisbecause it’smucheasiertoteachandgradethemechanicalaspectsofthetaskthanthecreativeelements.

Andingeneral,teachershavelittletraininginthefieldandareworkingfromcurriculadeveloped elsewherethattheyweregiventouse.Thisbook,however,focusesonthefirststep.Whileitcan’t covertheuniverseingeneral,itexaminesproblemsandtheirsolutionsinthecomputeruniverse insteadofdwellingontheexactprogrammingsyntaxneededtoimplementthosesolutions.

CODING, PROGRAMMING, ENGINEERING, AND COMPUTER SCIENCE

Anumberofdifferenttermsareusedtodescribeworkingwithsoftware.Thesetermshavenoexact definitions,althoughtheyhaveacquiredsomeroughmeanings.

Coding,afairlyrecenttermpopularizedaspartof“learningtocode,”canbeviewedasthe somewhatmechanicalworkoftranslation.Let’scompareittothejobofmedicalcoding.Whenyou visitadoctor,gettingadiagnosisistheeasypart.Thehardpartistranslatingthatdiagnosisinto oneoftheover100,000codesintheICDstandards,ICD-10atthetimeofwriting.ACertified ProfessionalCoderwhohaslearnedthesecodesknowsthat,whenadoctorcomesupwitha diagnosisof“struckbycow,”itshouldbeassignedcodeW55.2XA.Thisisactuallyharderthanmany codingjobsintheprogrammingspaceduetothesheernumberofcodes.Buttheprocessissimilar towhatacoderwoulddoifdirectedto“makethattextbold”onawebpage;acoderknowswhich codetousetomakethathappen.

TheICD-10standardissocomplicatedthatfewcodersknowitall.Instead,medicalcodersget certifiedinspecialtyareassuchas“Diseasesofthenervoussystem”or“Mentalandbehavioral disorders.”ThisisanalogoustoacoderbeingproficientinalanguagesuchasHTMLorJavaScript. But programming thatis,beingaprogrammer meansknowingmorethanaspecialtyareaor two.Thedoctorinthisscenarioisanalogoustoaprogrammer.Thedoctordeterminesadiagnosis byevaluatingthepatient.Thiscanbeprettycomplex.Forexample,ifapatienthasburnsandis soakingwet,isita“bizarrepersonalappearance”(R46.1)ora“burnduetowaterskisonfire,initial encounter”(V91.07XA)?Oncethedoctorhasadiagnosis,atreatmentplancanbedevised.The treatmentplanmustbeeffective;thedoctorprobablydoesn’twanttoseethesamepatient sufferingfromabadcaseof“parentaloverprotection”(Z62.1).

Justlikethedoctor,aprogrammerevaluatesaproblemanddeterminesasolution.Forexample, maybethere’saneedforawebsitethatallowspeopletorankICD-10codesintermsofsilliness.A programmerwoulddeterminethebestalgorithmsforstoringandmanipulatingthedata,the structureofthecommunicationbetweenthewebclientandserver,theuserinterface,andsoon. It’snotasimple“pluginthecode”sortofthing.

Engineering isthenextstepupincomplexity.Ingeneral,engineeringistheartoftakingknowledge andusingittoaccomplishsomething.YoucouldconsiderthecreationoftheICDstandardstobe engineering;ittookthelargefieldofmedicaldiagnosesandreducedthemtoasetofcodesthat couldbemoreeasilytrackedandanalyzedthandoctor’snotes.It’samatterofopinionasto whetherornotsuchacomplexsystemrepresents good engineering.Asanexampleofcomputer engineering,manyyearsagoIworkedonaprojecttobuildalow-costmedicalmonitorsuchas thosethatyouseeinhospitals.ThechargeIwasgivenwastomakeasystemthatadoctorornurse couldfigureouthowtouseinlessthan5minuteswithoutanydocumentation.Asyoumight imagine,thisrequiredmuchmorethanjustknowledgeofprogramming.AndIbeatthegoal my solutionendeduptakingabout30secondstolearntouse.

Programmingisoftenconfusedwithcomputerscience.Whilemanycomputerscientistsprogram, mostprogrammersaren’tcomputerscientists. Computer science isthestudyofcomputing. Computersciencediscoveriesareusedbyengineersandprogrammers.

Coding,programming,engineering,andcomputerscienceareindependentbutrelateddisciplines thatdifferinthetypeandamountofknowledgerequired.Beingacomputerscientist,engineer,or coderdoesn’tautomaticallymakesomeoneagoodprogrammer.Whilethisbookgivesyouataste ofhowengineersandcomputerscientiststhink,it’snotgoingtomakeyouone;thattypically requiresacollegeeducationcombinedwithsomehard-earnedrelevantexperience.Engineering andprogrammingaresimilartomusicorpainting they’repartskillandpartart.Theexpositionof bothaspectsinthisbookshouldhelpyoutoimproveyourskillsasaprogrammer.

THE LANDSCAPE

Computerdesignandprogrammingisahugefieldofstudy,whichIwon’tbeabletocoverhere.You canvisualizeitinlayers,asshowninFigure1.

KeepinmindthatFigure1isasimplificationandthatthelinesdividingthevariouslayersarenot ascleaninreality.

Themajorityofpeopleare users ofcomputersystems.You’reprobablyinthatcamprightnow. Therearespecializedsortsofuserscalled system administrators whosejobistokeepcomputer systemsworking.Theyinstallsoftware,manageuseraccounts,dobackups,andsoon.They typicallyhavespecialpowersnotgrantedtonormalusers.

Thepeoplewhowriteprogramslikewebpages,phoneapps,andmusicplayersare called application programmers.Theywritethesoftwarethatusersusetointeractwiththe computers,usingblocksthatothershavecreated.Applicationprogrammingisbeingtaughtinmost “learntocode”classesasifallprogrammershavetolearnishowtoimporttheseotherblocksand gluethemtogether.Althoughyoucangetawaywiththatalotofthetime,it’smuchbetterto actuallyunderstandboththoseblocksandtheglue.

Figure 1: Computer landscape

Applicationprogramsdon’ttalktothecomputerhardwaredirectly;that’swhere system programming comesintoplay.Systemprogrammersmakethebuildingblocksusedbyapplication programmers.Systemprogrammersneedtoknowabouthardwarebecausetheircodeinteracts withit.Oneofthegoalsofthisbookistoteachyouthingsyouneedtoknowinordertobeagood systemprogrammer.

Computerhardwareincludesnotonlythepartthatdoestheactualcomputingbutalsohowthat partconnectstotheworldoutside.Computerhardwareisexpressedas logic.It’sthesamelogic usedtowritecomputerprograms,andit’skeytounderstandingtheworkingsofthecomputer.The logicisconstructedfromvarioustypesofelectronic circuits.Circuitdesignisbeyondthescopeof thisbook,butyoucanlearnmoreaboutitbystudyingelectricalengineering.Consideradouble majorinelectricalengineeringandcomputerscienceifyouwanttoruletheworld.

Ofcourse,basicscienceunderpinsitall,providingeverythingfromourunderstandingofelectricity tothechemistryneededtocreatechips.

AsshowninFigure1,eachlevelbuildsontheonebeneathit.Thismeansthatpoordesignchoices orerrorsatlowerlevelsaffecteverythingabove.Forexample,adesignerrorinIntelPentium processorscirca1994causedsomedivisionoperationstoproduceincorrectresults.Thisaffected allsoftwarethatusedfloating-pointdivisionintheseprocessors.

Asyoucansee,systemprogrammingisatthebottomofthesoftwarehierarchy.It’ssimilarto infrastructure,likeroads,electricity,andwater.Beingagoodprogrammeralwaysmatters,butit mattersmoreifyou’reasystemprogrammer,becauseothersrelyonyourinfrastructure.Youcan alsoseethatsystemprogrammingissandwichedbetweenapplicationprogrammingandcomputer hardware,whichmeansyouneedtolearnsomethingaboutbothofthose.TheSanskrit word yoga translatesto“union,”andjustasyogapractitionersseektounifytheirmindandbody, systemprogrammersaretechno-yogiswhounifythehardwareandsoftware.

Youdon’thavetolearnsystemprogramminginordertoworkatoneoftheotherlevels.Butifyou don’t,you’llhavetofindsomeoneelsetohelpyoudealwithissuesoutofyourdomainratherthan beingabletofigurethemoutforyourself.Anunderstandingofthecoretechnologyalsoleadsto bettersolutionsathigherlevels.Thisisn’tjustmyopinion;checkoutthe2014blogpost“The ResourceLeakBugofOurCivilization”byVille-MatiasHeikkiläforasimilarview.

Thisbookalsoaimstocoveralotofretrohistory.Mostprogrammersaren’tlearningthehistoryof theircraftbecausethereissomuchmaterialtocover.Theresultisthatalotofpeoplearemaking mistakesthathavealreadybeenmade.Knowingsomeofthehistoryallowsyoutoatleastmake newandbettermistakesratherthanrepeatpastones.Bearinmindthatthehotnewtechnology you’reusingtodaywillquicklybecomeretrotomorrow.

Speakingofhistory,thisbookisjam-packedwithinterestingtechnologiesandthenamesoftheir inventors.Takesometimetolearnmoreaboutboththetechnologiesandthepeople.Mostofthe peoplementionedsolvedatleastoneinterestingproblem,andit’sworthlearningabouthowthey perceivedtheirworldandthewayinwhichtheyapproachedandsolvedproblems.There’sagreat exchangeinNealStephenson’s2008novel Anathem:

“Ouropponentisanalienstarshippackedwithatomicbombs.Wehaveaprotractor.”

“Okay,I’llgohomeandseeifIcanscroungeuparulerandapieceofstring.”

Notetherelianceonfundamentals.It’snot“Let’slookupwhattodoonWikipedia”or“I’llposta questiononStackOverflow”or“I’llfindsomepackageonGitHub.”Learningtosolveproblemsthat nobodyelsehassolvedisacrucialskill.

Manyoftheexamplesinthisbookarebasedonoldtechnologysuchas16-bitcomputers.That’s becauseyoucanlearnalmosteverythingyouneedtoknowfromthemandthey’reeasiertofitona page.

WHAT’S IN THIS BOOK

Thebookisconceptuallydividedintothreeparts.Thefirstpartexplorescomputerhardware,both whatitisandhowit’sbuilt.Thesecondpartexaminesthebehaviorofsoftwarerunningon hardware.Thelastpartcoverstheartofprogramming workingwithotherstoproducegood programs.

Chapter 1: The Internal Language of Computers

Thischapterstartsexploringthethree-year-oldmentality.Computersarebitplayers;theyherd bitsforaliving.You’lllearnwhattheyareandwhatcanbedonewiththem.We’llplaymake-believe toascribemeaningtobitsandtocollectionsofbits.

Chapter 2: Combinatorial Logic

Thischapterexaminestherationaleforusingbitsinsteadofdigitsandexploresthejustificationfor digitalcomputers.Thisincludesadiscussionofsomeoftheoldertechnologiesthatpavedtheway forwhatwehavetoday.Itcoversthebasicsofcombinatoriallogic.You’lllearnhowtobuildmore complicatedfunctionalityfrombitsandlogic.

Chapter 3: Sequential Logic

Hereyou’lllearnhowtouselogictobuildmemory.Thisincludeslearninghowtogeneratetime, becausememoryisnothingbutstatethatpersistsovertime.Thischaptercoversthebasicsof sequentiallogicanddiscussesvariousmemorytechnologies.

Chapter 4: Computer Anatomy

Thischaptershowshowcomputersareconstructedfromthelogicandmemoryelementsdiscussed intheearlierchapters.Anumberofdifferentimplementationmethodologiesareexamined.

Chapter 5: Computer Architecture

Inthischapter,we’llexploresomeoftheadd-onstothebasiccomputerthatwesawinChapter4. You’lllearnhowtheyprovideessentialfunctionalityandefficiency.

Chapter 6: Communications Breakdown

Computersneedtointeractwiththeoutsideworld.Thischaptercoversinputandoutput.Italso revisitsthedifferencebetweendigitalandanalogandhowwegetdigitalcomputerstoworkinan analogworld.

Chapter 7: Organizing Data

Nowthatyou’veseenhowcomputerswork,we’lllookathowtousethemeffectively.Computer programsmanipulatedatainmemory,andit’simportanttomapthewaymemoryisusedtothe problembeingsolved.

Chapter 8: Language Processing

Languageshavebeeninventedtomakeprogrammingcomputerseasierforpeople.Thischapter looksattheprocessofconvertinglanguagesintosomethingthatactuallyrunsoncomputers.

Chapter 9: The Web Browser

Alotofprogrammingisdoneforwebbrowsers.Thischapterlooksathowawebbrowserworks andteasesoutitsmaincomponents.

Chapter 10: Application and System Programming

Inthischapter,we’llwritetwoversionsofaprogramthatrunsattwoofthedifferentlevels fromFigure1.Thechapterexposesmanyofthedifferencesbetweenapplication-andsystem-level programming.

Chapter 11: Shortcuts and Approximations

Makingprogramsefficientisimportant.Thischapterexploressomeofthewaysinwhichwecan makeprogramsmoreefficientbyhavingthemavoidunnecessarywork.

Chapter 12: Deadlocks and Race Conditions

Manysystemsincludemorethanonecomputer.Thischapterexaminessomeoftheproblemsthat canoccurwhenwe’retryingtogetcomputerstocooperate.

Chapter 13: Security

Computersecurityisanadvancedtopic.Thischaptercoversthebasicswhilepuntingontheheavy math.

Chapter 14: Machine Intelligence

Thischapteralsocoversanadvancedtopic.Newapplicationsresultfromthecombinationofbig data,artificialintelligence,andmachinelearning fromdrivingyourcartodrivingyounutswith advertisements.

Chapter 15: Real-World

Considerations

Programmingisaverymethodicalandlogicalprocess.Buthumansareinvolvedinthe determinationofwhatandhowtoprogram,andhumansareoftenlackinginlogic.Thischapter discussessomeoftheissuesofprogrammingintherealworld.

Whenreadingthisbook,bearinmindthatmanyoftheexplanationsaresimplifiedandtherefore notcorrectdowntothesmallestdetail.Makingtheexplanationsperfectwouldrequiretoomuch distractingdetail.Don’tbesurprisedifyoudiscoverthisasyoulearnmore.Youcanconsiderthis booktobeaglossytravelbrochureforatriptocomputer-land.Itcan’tcovereverythingindetail, andwhenyougovisit,you’llfindplentyofsubtledifferences.

1

THEINTERNALLANGUAGEOFCOMPUTERS

Thewholepointoflanguageistobeabletocommunicateinformation.Yourjobasaprogrammeris togiveinstructionstocomputers.Theydon’tunderstandourlanguage,soyouhavetolearntheirs. Humanlanguageistheproductofthousandsofyearsofevolution.Wedon’tknowalotabouthowit evolved,sinceearlylanguagedevelopmentwasn’tadvancedtothepointthathistorycouldbe recorded.(Apparentlynobodywroteballadsaboutlanguagedevelopment.)Computerlanguages areadifferentstory,asthey’reafairlyrecentinventionthatoccurredlongafterthedevelopmentof humanlanguage,whichenablesustowriteaboutthem.

Humanandcomputerlanguagessharemanyofthesameelements,suchaswrittensymbolsand rulesfortheirproperarrangementandusage.Onethingthattheydon’tshareisnonwritten languageforms;computershavewrittenlanguageonly.

Inthischapter,you’llstarttolearnthelanguageofcomputers.Thisprocesshappensinstagesjust likewithhumanlanguage.Wehavetostartwithlettersbeforebuildinguptowordsandsentences. Fortunately,computerlanguagesaremuchsimplerthantheirhumancounterparts.

WHAT IS LANGUAGE?

Languageisaconvenientshortcut.Itallowsustocommunicatecomplexconceptswithouthavingto demonstratethem.Italsoallowsconceptstobeconveyedatadistance,evenviaintermediaries. Everylanguage whetherwritten,spoken,orexpressedinaseriesofgesturesorbybangingtwo rockstogether ismeaning encoded asasetofsymbols.Encodingmeaningassymbolsisn’tenough, though.Languageonlyworksifallcommunicatingpartieshavethesame context,sotheycanassign thesamemeaningtothesamesymbols.Forexample,theword Toto mightsuggestthedogfrom The Wizard of Oz tomanypeople,whileothersmightthinkoftheJapanesemanufacturerofheated toiletseats.IrecentlyencounteredmuchconfusionwhilediscussingclothingwithmyFrench exchangestudent.Itturnsoutthatthecommoninterpretationoftheword camisole inAmericais undershirt,butinFranceit’sstraitjacket!Inbothoftheseexamples,thesamesymbolscanbe distinguishedonlybycontext,andthatcontextisnotalwaysreadilydiscernible.Computer languageshavethisissuetoo.

WRITTEN LANGUAGE

Writtenlanguageisasequenceofsymbols.Weformwordsbyplacingsymbolsinaparticularorder. Forexample,inEnglishwecanformtheword yum byplacingthreesymbols(thatis,letters)in orderfromlefttorightasfollows: y u m.

Therearemanypossiblesymbolsandcombinations.Thereare26basicsymbols(A–Z)inEnglish ifweignorethingslikeupper-andlowercase,punctuation,ligatures,andsoon whichnative Englishspeakerslearnastoddlers.Otherlanguageshavedifferenttypesandnumbersofsymbols. Somelanguages,suchasChineseandJapaneseaswritteninkanji,haveaverylargenumberof symbolswhereeachsymbolisaworduntoitself.

Languagesalsousedifferentordering,suchasreadingrighttoleftinHebrewandverticallyin Chinese.Symbolorderisimportant: d o g isnotthesameas g o d

Althoughstylecaninsomewaysbeconsideredalanguageuntoitself,wedon’tdistinguishsymbols basedontypeface:a, a,and a areallthesamesymbol.

Threecomponentsframethetechnologyofwrittenlanguage,includingcomputerlanguage:

• Thecontainersthatholdsymbols

• Thesymbolsthatareallowedinthecontainers

• Theorderingofthecontainers

Somelanguagesincludemorecomplicatedrulesthatconstrainthepermittedsymbolsincontainers basedonthesymbolsinothercontainers.Forexample,somesymbolscan’toccupyadjacent containers.

THE BIT

We’llbeginwiththecontainer.Thismightbecalleda character inahumanlanguageanda bit for computers.Theterm bit isanawkwardmarriagebetween binary and digit.It’sawkward because binary isawordforsomethingwithtwoparts,whereas digit isawordforoneofthe10 symbols(0–9)thatmakeupoureverydaynumbersystem.You’lllearnwhyweusebitsinthenext chapter;fornow,it’senoughtoknowthatthey’recheapandeasytobuild.

Abitisbinary,whichmeansabitcontainercanholdonlyoneoftwosymbols,kindoflikethedot anddashfromMorsecode.Morsecodeusesjusttwosymbolstorepresentcomplexinformationby stringingthosesymbolstogetherindifferentcombinations.Theletter A isdot-dash,for example. B isdash-dot-dot-dot, C isdash-dot-dash-dot,andsoon.Theorderofthesymbolsis importantjustlikeinahumanlanguage:dash-dotmeans N,not A.

Theconceptofsymbolsisabstract.Itreallydoesn’tmatterwhattheystandfor;theycouldbeoff andon,dayandnight,orduckandgoose.Butremember,languagedoesn’tworkwithoutcontext. Thingswouldgetweirdfastifasenderthoughttheyweresaying U (dot-dot-dash),buttherecipient heard duck-duck-goose.

Intheremainderofthischapter,you’lllearnaboutsomeofthecommonwaysinwhichmeaningis assignedtobitsforcomputing.Keepinmindthatthereisalotofmake-believeinvolved for example,youmayrunintothingslike,“Let’spretendthatthisbitmeansblue.”Programming actuallyworksthatway,soeventhoughyou’llbelearningsomestandardbituses,don’tbeafraidto inventyourownwhenappropriate.

LOGIC OPERATIONS

Oneuseofbitsistorepresenttheanswerstoyes/noquestionssuchas“Isitcold?”or“Doyoulike myhat?”Weusetheterms true foryesand false forno.Questionslike“Where’sthedogparty?” don’thaveayes/noanswerandcan’tberepresentedbyasinglebit.

Inhumanlanguage,weoftencombineseveralyes/noclausesintoasinglesentence.Wemightsay, “Wearacoatifitiscoldorifitisraining”or“Goskiingifitissnowingandit’snotaschoolday.”

Anotherwayofsayingthosethingsmightbe“Wearcoatistrueifcoldistrueorrainingistrue”and

“Skiingistrueifsnowingistrueandschooldayisnottrue.”Theseare logic operationsthateach produceanewbitbasedonthecontentsofotherbits.

BooleanAlgebra

Justasalgebraisasetofrulesforoperatingonnumbers, Boolean algebra,inventedinthe1800sby EnglishmathematicianGeorgeBoole,isasetofrulesthatweusetooperateonbits.Aswithregular algebra,theassociative,commutative,anddistributiverulesalsoapply.

TherearethreebasicBooleanoperations, NOT, AND,and OR,aswellasonecomposite operation, XOR (shortfor“exclusive-or”),asdescribedhere:

NOT Thisoperationmeans“theopposite.”Forexample,ifabitisfalse, NOT thatbitwouldbetrue. Ifabitistrue, NOT thatbitwouldbefalse.

AND Thisoperationinvolves2ormorebits.Ina2-bitoperation,theresultistrueonlyifboththe first AND secondbitaretrue.Whenmorethan2bitsareinvolved,theresultistrueonlyif allbits aretrue.

OR Thisoperationalsoinvolves2ormorebits.Ina2-bitoperation,theresultistrueifthe first OR secondbitistrue;otherwise,theresultisfalse.Withmorethan2bits,theresultistrueif anybitistrue.

XOR Theresultofan exclusive-or operationistrueifthefirstandsecondbitshavedifferentvalues. It’seitherbutnotboth.Because“exclusive-or”isamouthful,weoftenusetheabbreviationXOR (pronounced“ex-or”).

Figure1-1summarizestheseBooleanoperationsgraphicallyinwhatareknownas truth tables. The inputs areoutsideoftheboxesandthe outputs areinside.Inthesetables,TstandsforTrueand FstandsforFalse.

Figure 1-1: Truth tables for Boolean operations

Figure1-2showshowthisworksfortheNOTandANDoperations.Wecanfindtheoutputby tracingapathfromtheinputorinputs.

Figure 1-2: Using truth tables

Asyoucansee,theNOToperationsimplyreversesthestateoftheinput.Ontheotherhand,the ANDoperationreturnstrueonlywhenbothinputsaretrue.

NOTE

The XOR operation is built from other operations. For example, the XOR of 2 bits,a and b, is the same thing as (a OR b) AND NOT (a AND b). This shows that basic Boolean operations can be combined in different ways to yield the same result.

DeMorgan’sLaw

Inthe1800s,BritishmathematicianAugustusDeMorganaddedalawthatappliesonlytoBoolean algebra,theeponymous De Morgan’s law.Thislawstatesthattheoperation a AND b isequivalentto theoperation NOT(NOT a OR NOT b),asshowninFigure1-3.

Figure 1-3: The truth table for De Morgan’s law

Noticethattheresultsof a AND b inthesecondcolumnareidenticaltotheresultslistedinthe final NOT(NOT a OR NOT b)column.ThismeansthatwithenoughNOToperations,wecanreplace ANDoperationswithORoperations(andviceversa).Thisisusefulbecausecomputersoperateon real-worldinputthat’snotundertheircontrol.Whileitwouldbeniceifinputswereofthe form cold or raining,they’reoften NOT cold or NOT raining.Similartodoublenegativesinlanguages suchasEnglish(“Wedidn’tnotgoskiing”),DeMorgan’slawisatoolthatletsusoperateon these negative logic propositionsinadditiontothe positive logic thatwe’vealreadyseen.Figure14illustratesthecoat-wearingdecisionforbothpositiveandnegativelogicforms.

Figure 1-4: Positive and negative logic

Ontheleft(positivelogic)side,wecanmakeourdecisionusingasingleORoperation.Ontheright (negativelogic)side,DeMorgan’slawallowsustomakeourdecisionusingasingleANDoperation. WithoutDeMorgan’slaw,we’dhavetoimplementthenegativelogiccaseas NOTnot-cold OR NOT not-raining.Althoughthatworks,thereisacostinpriceandperformancetoeachoperation,so minimizingoperationsminimizescosts.ThehardwarethatperformstheNOToperationcostsreal moneyand,asyou’lllearninthenextchapter,cascadingoperationsslowsthingsdown. DeMorgantellsusthatthisisequivalentto“coldandraining,”whichismuchsimpler.

REPRESENTING INTEGERS USING BITS

Let’smoveupthefoodchainandlearnhowtousebitstorepresentnumbers.Numbersaremore complicatedthanlogicbutmuchsimplerthanwords.

RepresentingPositiveNumbers

Wecommonlyusethe decimal numbersystembecauseitcorrespondstoouranatomy.Ten differentsymbolscalled digits cangointothecontainers:0123456789.Containersarestackedright toleft.Eachcontainerhasanamethatisseparatefromitscontents;wecalltherightmostcontainer theones,nextisthetens,thenthehundreds,thousands,andsoon.Thesenamesarealiasesfor powersof10;100 isone,101 isten,102 isonehundred,103 isonethousand.Thissystemis called base-10 since10isthebaseholdinguptheexponents.Thevalueofanumberisderivedfrom thesumoftheproductofeachcontainervalueandthevalueofitscontents.Forexample,the number5,028isthesumof5thousands,0hundreds,2tens,and8ones,or5×103 +0×102 +2× 101 +8×100,asshowninFigure1-5

Figure 1-5: The number 5,028 in decimal notation

Wecanuseasimilarapproachtomakenumbersusingbits.Sincewe’reusingbitsinsteadofdigits, weonlyhavetwosymbols:0and1.Butthat’snotaproblem.Indecimal,weaddacontainer wheneverwerunoutofroom;wecanfita9inasinglecontainerbutneedtwocontainersfor10. Thatworksinbinarytoo;wejustneedanewcontainerforanythinggreaterthana1.Therightmost containerwouldstillbetheones,butwhat’sthenextone?It’sthe twos.Thevalueofacontainerin decimalwherethereare10symbolsis10timesthatoftheoneontheright.Thus,inbinarywhere therearetwosymbols,thecontainervalueistwotimesthatoftheoneontheright.That’sallthere istoit!Thecontainervaluesarepowersof2,whichmeansit’sa base-2 systeminsteadofbase-10.

Table1-1listssomeofthepowersof2.Wecanuseitasareferencetounderstandthebinary representationofthenumber5,028.

Table 1-1: Powersof2

Eachnumberinthefar-rightcolumnofTable1-1representsthevalueofabinarycontainer.Figure 1-6showshowthenumber5,028canbewritteninbinary,usingessentiallythesameprocessthat weusedearlierfordecimalnotation.

Figure 1-6: The number 5,028 in binary

Theresultoftheconversiontobinaryis:

Asyoucansee,thenumber5,028inbinaryhasone4,096(212),zero2,048s(211),zero1,024s(210), one512(29),one256(28),andsoontomakeup1001110100100.Performingthesamesortof calculationthatwedofordecimalnumbers,wewrite1×212 +0×2

Substitutingthedecimalnumbers fromTable1-1,weget4,096+512+256+128+32+4,whichisequalto5,028. Wewouldsaythat5,028isafour-digitnumberindecimal.Inbinaryit’sa13-bitnumber. Thenumberofdigitsdeterminestherangeofvaluesthatwecanrepresentindecimal.Forexample, 100differentvaluesintherange0–99canberepresentedbytwodigits.Likewise,thenumberof bitsdeterminestherangeofvalueswecanrepresentinbinary.Forexample,2bitscanrepresent fourvaluesintherange0–3.Table1-2summarizesboththenumberandrangeofvaluesthatwe canrepresentwithdifferentnumbersofbits.

Table 1-2: RangesofBinaryNumberValues

Therightmostbitinabinarynumberiscalledthe least significant bit andtheleftmostbitiscalled the most significant bit,becausechangingthevalueoftherightmostbithasthesmallesteffecton thevalueofthenumberandchangingthevalueoftheleftmostbithasthegreatesteffect.Computer peoplearefondofthree-letteracronyms,orTLAsaswecallthem,sothesearecommonlyreferred toasthe LSB and MSB.Figure1-7showsanexampleofthenumber5,028heldin16bits.

You’llnoticethatwhilethebinaryrepresentationof5,028takes13bits,Figure1-7showsitin16 bits.Justlikeindecimal,wecanalwaysusemorecontainersthantheminimumrequiredby adding leading zeros ontheleft.Indecimal,05,028hasthesamevalueas5,028.Binarynumbersare oftenrepresentedthiswaybecausecomputersarebuiltaroundblocksofbits.

BinaryAddition

Nowthatyouknowhowtorepresentnumbersusingbinary,let’slookathowtodosimple arithmeticwithbinarynumbers.Indecimaladdition,weaddupeachdigitfromright(least significantdigit)toleft(mostsignificantdigit),andiftheresultisgreaterthan9,wecarrythe1. Similarly,weaddtogethereachbitinabinarynumber,goingfromtheleastsignificanttothemost significantbit,andiftheresultisgreaterthan1,wecarrythe1. Additionisactuallyabiteasierinbinarybecausethereareonly4possiblecombinationsof2bits comparedto100combinationsof2digits.Forexample,Figure1-8showshowtoadd1and5using binarynumbers,showingthenumberbeingcarriedaboveeachcolumn.

Figure 1-7: MSB and LSB

Figure 1-8: Binary addition

Thenumber1is001inbinary,whilethenumber5is101because(1×4)+(0×2)+(1×1)=5.To addthebinarynumbers001and101together,westartwiththeleastsignificantbitinthe rightmostcolumn.Addingthebinarynumbers1and1inthatcolumngivesus2,butwedon’thave asymbolfor2inbinary.Butweknowthat2isactually10inbinary([1×2]+[0×1]=2),soweput 0asthesumandcarrythe1tothenextdigit.Becausethemiddlebitsarezeros,weonlyhave1, whichwecarriedoverfrombefore,asthesum.Thenweaddthedigitsintheleftmostcolumn:0 plus1issimply1inbinary.Thefinalresultisthebinary110,or6indecimalnotation,whichis whatyouwouldgetbyadding1and5.

Youmightnoticethattherulesforbinaryadditioncanbeexpressedintermsofthelogical operationsthatwediscussedpreviously,asFigure1-9illustrates.We’llseeinChapter2thatthisis infacthowcomputerhardwaredoesbinaryaddition.

Figure 1-9: Binary addition using logical operations

Whenweadd2bitstogether,thevalueoftheresultistheXORofthe2bits,andthevalueofthe carryistheANDofthe2bits.YoucanseethatthisistrueinFigure1-9,whereadding1and1in binaryresultsin10.Thismeansthatthecarryvalueis1,whichiswhatyougetbyperformingthe expression(1 AND 1).Likewise,theexpression(1 XOR 1)yields0,whichisthevaluethatweassign tothebitpositionitself.

Adding2bitsisanoperationthatrarelyhappensinisolation.ReferringbacktoFigure1-8,it appearsthatwe’readding2bitstogetherineachcolumn,butwe’rereallyadding3becauseofthe carry.Fortunately,wedon’tneedtolearnanythingnewtoadd3bitstogether(becauseA+B+Cis thesameas(A+B)+C,accordingtotheassociativerule),sowecanadd3bitstogetherusingapair of2-bitadds.

Whathappenswhentheresultofadditiondoesn’tfitinthenumberofbitsthatwehave?This resultsin overflow,whichhappenswheneverwehaveacarryfromthemostsignificantbit.For example,ifwehave4-bitnumbers,andadd1001(910)to1000(810),theresultshouldbe10001 (1710),butitwillendupbeing0001(110)becausethere’snoplaceforthemostsignificantbit.As we’llseeinmoredetaillater,computershavea condition code register,whichisaplacethatholds oddpiecesofinformation.Oneoftheseisan overflow bit,whichholdsthecarryvaluefromthemost significantbit.Wecanlookatthisvaluetodeterminewhetherornotoverflowoccurred.

You’reprobablyawarethatyoucansubtractonenumberfromanotherbyaddingthenegativeof thatnumber.We’lllearnhowtorepresentnegativenumbersinthenextsection.Borrowingbeyond themostsignificantbitiscalled underflow.Computershaveaconditioncodeforthistoo.

RepresentingNegativeNumbers

Allofthenumberswerepresentedusingbinaryinthelastsectionwerepositive.Butlotsofrealworldproblemsinvolvebothpositiveandnegativenumbers.Let’sseehowwecanusebitsto representnegativenumbers.Forexample,let’sassumethatwehave4bitstoplaywith.Asyou learnedinthelastsection,4bitscanrepresent16numbersintherangeof0through15.Just becausewecanhold16numbersin4bitsdoesn’tmeanthatthosenumbershavetobe0through 15.Remember,languageworksthroughmeaningandcontext.Thatmeansthatwecandevisenew contextsinwhichwecaninterpretbits.

SignandMagnitude

A sign iscommonlyusedtodistinguishnegativenumbersfrompositiveones.Thesignhastwo values,plusandminus,soitcanberepresentedusingabit.We’llarbitrarilyusetheleftmostbit (MSB)forthesign,leavingus3bitsthatcanrepresentanumberbetween0and7.Ifthesignbitis 0,wetreatthatnumberaspositive.Ifit’s1,wetreatitasnegative.Thisletsusrepresent15 differentpositiveandnegativenumbersintotal,not16,becausethereisbothapositive0anda negative0.Table1-3showshowthisallowsustorepresentthenumbersbetween–7and+7. Thisiscalled sign and magnitude representationbecausethere’sabitthatrepresentsasignand bitsthatrepresentthemagnitude,orhowfarthevalueisfromzero.

Signandmagnituderepresentationisnotusedmuchfortworeasons.First,bitscostmoneyto build,sowedon’twanttowastethembyhavingtwodifferentrepresentationsforzero;we’dmuch ratherusethatbitcombinationtorepresentanothernumber.Second,arithmeticusingXORand ANDdoesn’tworkusingthisrepresentation.

Table 1-3: SignandMagnitudeBinaryNumbers

Let’ssaythatwewanttoadd+1to–1.We’dexpecttoget0,butusingsignandmagnitude representationwegetadifferentresult,asshowninFigure1-10

Figure 1-10: Sign and magnitude addition

Asyoucansee,0001representspositive1inbinary,becauseitssignbitis0.The1001represents–1inbinary,becausethesignbitis1.AddingthesetogetherusingXORandANDarithmeticgivesus 1010.Thisevaluatesto–2indecimalnotation,whichisnotthesumof+1and–1. Wecouldmakesignandmagnitudearithmeticworkbyusingmorecomplicatedlogic,butthere’s valueinkeepingthingsassimpleaspossible.Let’sexploreafewotherwaysofrepresenting numberstofindabetterapproach.

One’sComplement

Anotherwaytogetnegativenumbersistotakepositivenumbersandflipallthebits,whichis called one’s complement representation.Wepartitionthebitsinamannersimilartosignand magnitude.Inthiscontext,wegetacomplementusingtheNOToperation.Table1-4shows–7 through7usingone’scomplement.

Table 1-4: One’sComplementBinaryNumbers

Asyoucansee,flippingeachbitof0111(+7)yields1000(–7).

One’scomplementrepresentationstillhastheproblemoftwodifferentrepresentationsforzero.It stilldoesn’tletusperformadditioneasily,either.Togetaroundthis,weuse end-around carry to add1totheLSBifthereisacarryoutofthemostsignificantpositioninordertogetthecorrect result.Figure1-11illustrateshowthisworks.

Another random document with no related content on Scribd:

OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied warranties or the exclusion or limitation of certain types of damages. If any disclaimer or limitation set forth in this agreement violates the law of the state applicable to this agreement, the agreement shall be interpreted to make the maximum disclaimer or limitation permitted by the applicable state law. The invalidity or unenforceability of any provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the trademark owner, any agent or employee of the Foundation, anyone providing copies of Project Gutenberg™ electronic works in accordance with this agreement, and any volunteers associated with the production, promotion and distribution of Project Gutenberg™ electronic works, harmless from all liability, costs and expenses, including legal fees, that arise directly or indirectly from any of the following which you do or cause to occur: (a) distribution of this or any Project Gutenberg™ work, (b) alteration, modification, or additions or deletions to any Project Gutenberg™ work, and (c) any Defect you cause.

Section 2. Information about the Mission of Project Gutenberg™

Project Gutenberg™ is synonymous with the free distribution of electronic works in formats readable by the widest variety of computers including obsolete, old, middle-aged and new computers. It exists because of the efforts of hundreds of volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the assistance they need are critical to reaching Project

Gutenberg™’s goals and ensuring that the Project Gutenberg™ collection will remain freely available for generations to come. In 2001, the Project Gutenberg Literary Archive Foundation was created to provide a secure and permanent future for Project Gutenberg™ and future generations. To learn more about the Project Gutenberg Literary Archive Foundation and how your efforts and donations can help, see Sections 3 and 4 and the Foundation information page at www.gutenberg.org.

Section 3. Information about the Project Gutenberg Literary Archive Foundation

The Project Gutenberg Literary Archive Foundation is a nonprofit 501(c)(3) educational corporation organized under the laws of the state of Mississippi and granted tax exempt status by the Internal Revenue Service. The Foundation’s EIN or federal tax identification number is 64-6221541. Contributions to the Project Gutenberg Literary Archive Foundation are tax deductible to the full extent permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up to date contact information can be found at the Foundation’s website and official page at www.gutenberg.org/contact

Section 4. Information about Donations to the Project Gutenberg Literary Archive Foundation

Project Gutenberg™ depends upon and cannot survive without widespread public support and donations to carry out its mission of increasing the number of public domain and licensed works that can be freely distributed in machine-readable form

accessible by the widest array of equipment including outdated equipment. Many small donations ($1 to $5,000) are particularly important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating charities and charitable donations in all 50 states of the United States. Compliance requirements are not uniform and it takes a considerable effort, much paperwork and many fees to meet and keep up with these requirements. We do not solicit donations in locations where we have not received written confirmation of compliance. To SEND DONATIONS or determine the status of compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where we have not met the solicitation requirements, we know of no prohibition against accepting unsolicited donations from donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make any statements concerning tax treatment of donations received from outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation methods and addresses. Donations are accepted in a number of other ways including checks, online payments and credit card donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About Project Gutenberg™ electronic works

Professor Michael S. Hart was the originator of the Project Gutenberg™ concept of a library of electronic works that could be freely shared with anyone. For forty years, he produced and

distributed Project Gutenberg™ eBooks with only a loose network of volunteer support.

Project Gutenberg™ eBooks are often created from several printed editions, all of which are confirmed as not protected by copyright in the U.S. unless a copyright notice is included. Thus, we do not necessarily keep eBooks in compliance with any particular paper edition.

Most people start at our website which has the main PG search facility: www.gutenberg.org.

This website includes information about Project Gutenberg™, including how to make donations to the Project Gutenberg Literary Archive Foundation, how to help produce our new eBooks, and how to subscribe to our email newsletter to hear about new eBooks.

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.