Figure 4.2

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Figure 4.2

aetesaki
Bought the book too to check out what information and ideas I could gather from that source too. As such I found this short Hack assembler code, as written in the book:

	@i	// i refers to some mem. location
	M=1	// i=1
	@sum	// sum refers to some mem. location
	M=0	// sum=0
(LOOP)
	@i
	D=M	// D=M
	@100
	D=D-A	// D=i-100
	@END
	D;JGT	// If (i-100)>0 goto END
	@i
	D=M	// D=i
	@sum
	M=M+D	// sum=sum+i
	@i
	M=M+1	// i=i+1
	@LOOP
	0;JMP	// Goto LOOP
(END)
	@END
	0;JMP	// Infinite loop
 
Rearranging the loop to always keep @i in the Data-register at each end of the loop, and reusing the @LOOP-jump instruction to also work as the halt-loop, I cut 6 instructions from the code:

// setup
	// initiate sum
	@sum	
	M=0		
	// initiate @i, and load in D
	@i	
	MD=1
(LOOP)
	// add current @i to @sum
	@sum
	M=M+D
	
	// subtract 100 from D
	@100
	D=D-A
	// jump to HLT if D >= 0
	@HLT
	D;JGE
	
	// load @i, increase, store, and jump to LOOP
	@i
	MD=M+1
	@LOOP
(HLT)
	0;JMP
Reply | Threaded
Open this post in threaded view
|

Re: Figure 4.2

WBahn
Administrator
The code in the book generally tries to match a straightforward higher-level understanding of the code. It can often be optimized quite a bit, but it makes it harder for most people, especially people brand new to assembly language, to follow.