physics 124: lecture 8 · phys 124: lecture 8 2 binary decimal hexadecimal 0000 0000 0 0x00...
TRANSCRIPT
Physics124:Lecture8
OddsandEndsBinary/Hex/ASCII
Memory&PointersinCDecibels&dBScalesCoherentDetection
AdaptedfromTomMurphy’slectures
Binary,HexadecimalNumbers• Computersstoreinformationinbinary– 1or0,correspondingtoVCC and0volts,typically– theCCsubscriptoriginatesfrom“collector”oftransistor
• Becomefamiliarwithbinarycountingsequence
2Phys124:Lecture8
binary decimal hexadecimal
00000000 0 0x00
0000 0001 1 0x01
00000010 2 0x02
00000011 2+1=3 0x03
00000100 4 0x04
00000101 4+1 =5 0x05
etc.
1111 1100 128+64+32+16+8+4 =252 0xfc
11111101 128+64+32+16+8+4+1=253 0xfd
11111110 128+64+32+16+8+4+2=254 0xfe
11111111 128+64+32+16+8+4+2+1=255 0xff
BinarytoHex:easy!• Noteseparationofprevious8-bit(one-byte)numbersintotwo4-bitpieces(nibbles)– makesexpressioninhex(base-16;4-bits)natural
Phys124:Lecture8 3
binary hexadecimal decimal
0000 0 0
0001 1 1
0010 2 2
0011 3 3
0100 4 4
0101 5 5
0110 6 6
0111 7 7
1000 8 8
1001 9 9
1010 A(lowercasefine) 10
1011 B 11
1100 C 12
1101 D 13
1110 E 14
1111 F 15
0 1 2 3 4 5 6 7
0 NUL ^@ null (\0) DLE ^P SP space 0 @ P ` p
1 SOH ^A startofhdr DC1 ^Q ! 1 A Q a q
2 STX ^B starttext DC2 ^R “ 2 B R b r
3 ETX ^C endtext DC3 ^S # 3 C S c s
4 EOT ^D endtrans DC4 ^T $ 4 D T d t
5 ENQ ^E NAK ^U % 5 E U e u
6 ACK ^F acknowledge SYN ^V & 6 F V f v
7 BEL ^G bell ETB ^W ‘ 7 G W g w
8 BS ^H backspace CAN ^X ( 8 H X h x
9 HT ^I horiz.tab(\t) EM ^Y ) 9 I Y i y
A LF ^J linefeed (\r) SUB ^Z * : J Z j z
B VT ^K verticaltab ESC escape + ; K [ k {
C FF ^L formfeed FS , < L \ l |
D CR ^M carriage ret(\n) GS - = M ] m }
E SO ^N RS . > N ^ n ~
F SI ^O US / ? O _ o DELPhys124:Lecture8 4
firsthexdigitsecond
hexdigit
ASCIITable inHex
ASCIIinHex
• NotethepatternsandconveniencesintheASCIItable– 0thru9ishex0x30to0x39(justadd0x30)– A-Zparallelsa-z;justadd0x20
• startsat0x41and0x61,soHis8th letter, is0x48,etc.
– thefirst32charactersarecontrolcharacters,oftenrepresentedasCtrl-C,denoted̂ C,forinstance• associatedcontrolcharactersmirror0x40to0x5F• putcommoncontrolcharacters inred;useful toknowinsomeprimitiveenvironments
Phys124:Lecture8 5
Two’sComplement• Unsignedaredirectbinaryrepresentation• Signedintegersusuallyfollow“two’scomplement”
– rule:togetneg.number, flipallbitsandaddone• example:-2:00000010à 11111101+1=11111110• Alsocalled“bias”,2" =256forsingleprecision,2$% fordoubleprecision
– addingpos.&neg.à 00000000(ignoreoverflow bit)Phys124:Lecture8 6
binary hex unsigned 2’scomplement
00000000 0x00 0 0
00000001 0x01 1 1
00000010 0x02 2 2
01111111 0x7F 127 127
10000000 0x80 128 -128
1000 0001 0x81 129 -127
11111110 0xFE 254 -2
11111111 0xFF 255 -1
FloatingPointNumbers• MoststandardisIEEEformat
– http://en.wikipedia.org/wiki/IEEE_754-1985– https://en.wikipedia.org/wiki/IEEE_floating_point#IEEE_754-2008
𝟎. 𝟏𝟓𝟔𝟐𝟓$, = 𝟎. 𝟎𝟎𝟏𝟎𝟏- =2./ + 2.1 = +𝟏.𝟎𝟏-×2./• Threeparts:sign, mantissa, exponent
– sign:0ispositive,1isnegative;mantissa,1isimplied– exponent:biasby127,i.e.,127-3-124 =0b01111100– single-precision(float)has32bits(1,8,23,resp.)
• 7digits,10±38: log(10)/log(2)=3.32,so223 ≈107;±127/3.32≈38– doubleprecision(double)has64bits(1,11,52,resp.)
• 16digits,10±308
• Theactualconvention isnotcriticalforustounderstand,asmuchas:– limitationstofiniterepresentation– spaceallocationinmemory:just32or64bitsof1’s&0’s
Phys 124:Lecture8 7
Phys124:Lecture8 8
Arrays&StorageinC
• Wecanholdmorethanjustonevalueinavariable– buttheprogramneeds toknowhowmanyplacestosavein
memory• Examples:
– wecaneither sayhowmanyelements toallowandleavethemunset;sayhowmanyelements andinitialize allelements tozero; leaveoutthenumberofelements andspecify explicitly; specifynumberofelements andcontents
– characterarraysarestrings– stringsmustendin‘\0’ tosignaltheend– mustallow room:char name[4]=“Bob”
• fourthelementis‘\0’ bydefault
int i[8], j[8]={0}, k[]={9,8,6,5,4,3,2,1,0};double x[10], y[10000]={0.0}, z[2]={1.0,3.0};char name[20], state[]=“California”;
Phys124:Lecture8 9
IndexingArraysint i,j[8]={0},k[]={2,4,6,8,1,3,5,7};double x[8]={0.0},y[2]={1.0,3.0},z[8];char name[20],state[]="California";
for (i=0; i<8; i++){z[i] = 0.0;printf(”j[%d] = %d, k[%d] = %d\n",i,j[i],i,k[i]);
}name[0]='T';name[1]='o';name[2]='m';name[3] = '\0';printf("%s starts with %c and lives in %s\n",name,name[0],state);
• Indexarrayintegers, startingwithzero• Sometimes initializeinloop(z[] above)• Stringassignmentawkwardoutsideofdeclaration line
– #include <string.h> provides“useful”stringroutines• doneautomatically inArduino,butalsoStringtypemakesmanythingseasier
Phys124:Lecture8 10
MemoryAllocationinArrays• state[]=“California”;→
• name[11]=“Bob”;→
– empty spacesattheendcouldcontainanyrandomgarbage
• int i[] = {9,8,7,6,5,4,3,2};→
– indexingi[8] isoutofbounds,andwilleither causeasegmentation fault(ifwriting),orreturngarbage(ifreading)
C a l i f o r n i a \0
B o b \0
9 8 7 6 5 4 3 2
eachblockis8-bitchar
eachblockis16or32-bitint
Phys124:Lecture8 11
Multi-DimensionalArrays
• Cisarow-majorlanguage:thefirstindexdescribeswhichrow(notcolumn),andarrangedinmemoryrow-by-row– memoryis,afterall, arrangedone-dimensionally
• Havetheoptionoftreatinga2-Darrayas1-D– arr[5] = arr[1][1] = 3
• Canhavearraysof2,3,4,…dimensions
int i,j,arr[2][4];
for (i=0; i<2; i++){for (j=0; j<4; j++){arr[i][j] = 4+j-2*i;
}} 4 5 6 7 2 3 4 5
4 5 6 7
2 3 4 5
0
1
0 1 2 3
i
j
inmemoryspace:
Phys124:Lecture8 12
Arraysandfunctions• Howtopassarraysintoandoutoffunctions?• AnarrayinCisactuallyhandledasa“pointer”
– apointer isadirectiontoaplaceinmemory• Apointertoavariable’saddressisgivenbythe&symbol
– youmayremember thisfromscanf functions• Foranarray,thenameisalreadyanaddress
– because it’sablockofmemory, thenamebyitselfdoesn’t containauniquevalue
– instead, thenamereturns theaddressofthefirstelement– ifwehaveint arr[i][j];
• arr and&arr[0] and&arr[0][0] meanthesamething:theaddressofthefirstelement
• Bypassinganaddresstoafunction,itcanmanipulatethecontentsofmemorydirectly,withouthavingtopassbulkyobjectsbackandforthexplicitly
Phys124:Lecture8 13
Example:3x3matrixmultiplication
void mm3x3(double a[], double b[], double c[])
// Takes two (3x3 matrix) pointers, a, b, stored in 1-d arrays nine// elements long (row major, such that elements 0,1,2 go across a// row, and 0,3,6 go down a column), and multiplies a*b = c.// Dimensionality and encoding of the arguments are assumed.{
double *cptr; // define a pointer variable to doubleint i,j;
cptr = c; // without *, it’s address; point to addr. for c
for (i=0; i<3; i++){for (j=0; j<3; j++){
*cptr++ = a[3*i]*b[j] + a[3*i+1]*b[j+3] + a[3*i+2]*b[j+6];// calc value to stick in current cptr location, then// increment the value for cptr to point to next element// * gets at contents
}}
}
Phys124:Lecture8 14
mm3x3,expanded
• Thefunctionisbasicallydoingthefollowing:
– whichyoucouldconfirmisthepropersetofoperationsformultiplyingout3×3matrices
*cptr++ = a[0]*b[0] + a[1]*b[3] + a[2]*b[6];*cptr++ = a[0]*b[1] + a[1]*b[4] + a[2]*b[7];*cptr++ = a[0]*b[2] + a[1]*b[5] + a[2]*b[8];
*cptr++ = a[3]*b[0] + a[4]*b[3] + a[5]*b[6];*cptr++ = a[3]*b[1] + a[4]*b[4] + a[5]*b[7];*cptr++ = a[3]*b[2] + a[4]*b[5] + a[5]*b[8];
*cptr++ = a[6]*b[0] + a[7]*b[3] + a[8]*b[6];*cptr++ = a[6]*b[1] + a[7]*b[4] + a[8]*b[7];*cptr++ = a[6]*b[2] + a[7]*b[5] + a[8]*b[8];
Phys124:Lecture8 15
Notesonmm3x3• Thefunctionis constructedtodealwith1-dinsteadof2-darrays– 9elementsinsteadof3×3– itcouldhavebeendoneeitherway
• Thereisapointer,*cptrbeingused– byspecifyingcptr asadoublepointer,andassigningitsaddress(justcptr)toc,wecanstockthememorybyusing“pointermath”
– cptr istheaddress;*cptr isthevalueatthataddress– justlike&x_val isanaddress,whilex_val containsthevalue
– cptr++ bumpstheaddressbytheamountappropriatetothatparticulardatatype(doubleprec.here),called“pointermath”
– *cptr++ = value; assignsvalueto*cptr,thenadvancesthecptr count
Phys124:Lecture8 16
Usingmm3x3
• passingjustthenames(addresses)ofthearrays– fillingouta andb, butjustmaking spaceforc– notefunctiondeclarationbeforemain
#include <stdio.h>
void mm3x3(double a[], double b[], double c[]);
int main(){
double a[]={1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0};double b[]={1.0, 2.0, 3.0, 4.0, 5.0, 4.0, 3.0, 2.0, 1.0};double c[9];
mm3x3(a,b,c);
printf("c = %f %f %f\n",c[0],c[1],c[2]);printf(" %f %f %f\n",c[3],c[4],c[5]);printf(" %f %f %f\n",c[6],c[7],c[8]);
return 0;}
Phys124:Lecture8 17
double a[3][3]={{1.0, 2.0, 3.0},{4.0, 5.0, 6.0},{7.0, 8.0, 9.0}};
double b[3][3]={{1.0, 2.0, 3.0},{4.0, 5.0, 4.0},{3.0, 2.0, 1.0}};
double c[3][3];
mm3x3(a,b,c);
Anotherwaytoskinthecat
• Here,wedefinethearraysas2-d,knowingthatinmemorytheywillstillbe1-d– wewillgetcompilerwarnings,butthethingwillstillwork– notarecommended approach,justpresentedherefor
educational purposes– Notethatwecouldreplacea with&a[0][0] inthe
functioncall,andthesame fortheothers,andgetnocompiler errors
Decibels
• Soundismeasuredindecibels,ordB– asaremanyradio-frequency(RF)applications
• Logarithmicscale– commonfeatureisthatevery10dBisafactorof10inpower/intensity
– otherhandymetrics• 3dBis2ו 7dBis5ו obviouslypiling2× and5× is10×,whichis10dB=3dB+7dB
– decibelsthuscombinelikelogarithms:additionrepresentsmultiplicativefactors
Phys124:Lecture8 18
Phys124:Lecture8 19
SoundIntensity
• Soundrequiresenergy(pushingatoms/moleculesthroughadistance),andthereforeapower
• Soundischaracterizedindecibels(dB),accordingto:– soundlevel =10×log(I/I0)=20×log(P/P0)dB– I0 =10−12 W/m2 isthethresholdpowerintensity (0dB)– P0 =2×10−5 N/m2 isthethresholdpressure (0dB)
• atmosphericpressureisabout105 N/m2
• 20 outfrontaccountsforintensitygoinglikeP2
• Examples:– 60dB(conversation) means log(I/I0)=6,soI =10−6W/m2
• andlog(P/P0)=3,soP =2×10−2 N/m2 =0.0000002atmosphere!!– 120dB(painthreshold) means log(I/I0)=12,soI =1W/m2
• andlog(P/P0)=6,soP =20N/m2 =0.0002atmosphere– 10dB(barelydetectable) means log(I/I0)=1,soI =10−11W/m2
• andlog(P/P0)=0.5,soP ≈ 6×10−5 N/m2
Phys124:Lecture8 20
Soundhittingyoureardrum• Pressurevariationsdisplacemembrane(eardrum,microphone)whichcanbeusedtomeasuresound– myspeakingvoiceismovingyoureardrumbyamere1.5×10-4 mm=150nm=1/4wavelengthofvisiblelight!
– thresholdofhearingdetects5×10-8 mmmotion,one-halfthediameterofasingleatom!!!
– painthresholdcorrespondsto0.05mmdisplacement• Earignoreschangesslowerthan20Hz– sothoughpressurechangesevenasyouclimbstairs,itistooslowtoperceiveassound
• Eardrumcan’tbewiggledfasterthanabout20kHz– justliketryingtowiggleresonantsystemtoofastproducesnosignificantmotion
A-weighting:accountforrelativeloudness
Phys124:Lecture8 21
• Relatedtomeasurementofsoundpressurelevel• DefinedinstandardIEC61672:2003,forenvironmentaland
industrialnoise• Accountsforlowsensitivityofhumanearatlowfrequencies,
reducesimportanceoflowfreq.inhumanimpactassessmentsOtherweightings available:B,C,D
Phys124:Lecture8 22http://www.dot.ca.gov/dist2/projects/sixer/loud.pdf
SoundscalesnotforhumansNoiseCriterion(NC)
Phys124:Lecture8 23
dBScales• Intheradio-frequency(RF)world,dBisusedseveralways
– dBisarelative scale:aratio:oftencharacterizingagainorloss• +3dBmeansafactoroftwomore• −17dBmeansafactorof50loss,or2%throughput
– dBm isanabsolute scale,inmilliwatts: 10×log(P/1mW)• 0dBm is1mW,a30dBm signalis1 W• 36dBm is4W(note6dBistwo3dB,eachafactorof2à 4×)• −27dBm is2µW
– dBc issignalstrengthrelative tothecarrier• oftencharacterizesdistortionfromsinusoid• −85dBc meansanydistortionsarealmostnineorders-of-magnitudeweakerthanthemainsinusoidal“carrier”
• Voltageistheequivalentofsoundpressure,anamplitude:10×log 89:;<=
89:;<>= 20×log ?9@ABC;=
?9@ABC;>dB
Phys124:Lecture8 24
CoherentDetection
• Sometimesfightingtodiscernsignalagainstbackgroundnoise– photogate inbrightsetting,forinstance
• Oneapproachiscoherentdetection– modulatesignalatknownphase,inON/OFFpatternat50%dutycycle
– accumulate(add)in-phaseparts,whilesubtractingout-of-phaseparts
– haveintegratorperformaccumulation,ortryinsoftware• butifbackgroundisnoisyinadditiontohigh,integrationbetter
– basicallybackgroundsubtraction– gainmorethegreaterthenumberofcyclesintegrated
Phys124:Lecture8 25
RawSignal,Background,andNoise
Phys124:Lecture8 26
ModulatedSignal;stillhardtodiscern
Phys124:Lecture8 27
Integration,subtracting“OFF”portions
Phys124:Lecture8 28
ExpressedinElectronics
Phys124:Lecture8 29
firstop-ampjustinverting;secondsumstwoinputs,onlyoneonatatimehaseffectofaddingpartswhenRef=+1,subtractingwhereRef=-1
clears“memory”ontimescale ofτint =RintCcouldalsoconceiveofperformingmathinsoftware
Lock-indetection
Phys124:Lecture8 30
https://www.zhinst.com/applications/principles-of-lock-in-detection
Announcements
• ProjectProposalsdueintwoweeksFriday,Nov.3• Lab3duenextweekMon/Tue(10/23,10/24)• Lab4duein2+weeksTue/Wed(11/6,11/7)• MidtermWed.11/8
Phys124:Lecture8 31