140 likes | 280 Vues
This document provides detailed instructions for implementing a factorial calculation and hex-to-ASCII conversion in stack-based programming. It includes a step-by-step process that outlines the handling of various conditions, such as checking for input pin statuses and managing data stack operations. The instructions emphasize the importance of managing control flow, such as jumps and repetitive loops, to efficiently compute results. The document serves as a comprehensive guide for advanced users looking to enhance their skills in low-level programming techniques.
E N D
Other WC16 Instructions Lecture L7.4
when lit => tload <= '1'; nload <= '1'; tsel <= "001"; dpush <= '1'; LIT Load inline literal to T and push data stack.
when jb0LO => pload <= not B(0); psel <= '0'; pinc <= B(0); JB0LO Jump if input pin B0 is LO.
when jb0HI => pload <= B(0); psel <= '0'; pinc <= not B(0); JB0HI Jump if input pin B0 is HI
Hex2asc.whp \ Convert hex to ASCII HEX : hex2asc ( n -- asc ) 0F AND \ mask upper nibble DUP 9 > \ if n > 9 IF 37 + \ add $37 ELSE 30 + \ else add $30 THEN ; : main ( -- ) BEGIN waitb0 S@ DUP DIG! waitb0 hex2asc DIG! AGAIN ;
LIT, --2 X"000f", --3 andd, --4 dup, --5 LIT, --6 X"0009", --7 gt, --8 JZ, --9 X"0010", --a LIT, --b X"0037", --c plus, --d JMP, --e X"0013", --f LIT, --10 X"0030", --11 plus, --12 RET, --13 : hex2asc ( n -- asc ) 0F AND \ mask upper nibble DUP 9 > \ if n > 9 IF 37 + \ add $37 ELSE 30 + \ else add $30 THEN ;
when jmp => pload <= '1'; psel <= '0'; pinc <= '0'; JMP Jump to inline address.
when jz => -- pop flag pload <= not z; psel <= '0'; pinc <= z; tload <= '1'; nload <= '1'; tsel <= "111"; nsel <= "01"; dpop <= '1'; -- z <= '0' if T = all zeros JZ Jump if all bits in T are ‘0’ and pop T
BEGIN…WHILE…REPEAT BEGIN <words> <flag> WHILE <words> REPEAT
Factorial x = 1 i = 2 DO WHILE i <= n x = x * i i = i + 1 ENDDO factorial = x : factorial ( n -- n! ) 1 2 ROT \ x i n BEGIN \ x i n 2DUP <= \ x i n f WHILE \ x i n -ROT TUCK \ n i x i * SWAP \ n x i 1+ ROT \ x i n REPEAT \ x i n 2DROP ; \ x
\ Example of BEGIN...WHILE...REPEAT : UM* ( u1 u2 - upL upH ) 0 mpp mpp mpp mpp mpp mpp mpp mpp mpp mpp mpp mpp mpp mpp mpp mpp ROT_DROP ; : * ( n1 n2 -- n3 ) UM* DROP ; : factorial ( n -- n! ) 1 2 ROT \ x i n BEGIN \ x i n OVER OVER <= \ x i n f WHILE \ x i n -ROT TUCK \ n i x i * SWAP \ n x' i 1+ ROT \ x' i' n REPEAT \ x i n DROP DROP ; \ x : main ( -- ) BEGIN waitB0 S@ DUP DIG! waitB0 factorial DIG! AGAIN ; Fact16.whp
LIT, --1a X"0001", --1b LIT, --1c X"0002", --1d rot, --1e over, --1f over, --20 lte, --21 JZ, --22 X"002d", --23 mrot, --24 tuck, --25 CALL, --26 X"0016", --27 swap, --28 plus1, --29 rot, --2a JMP, --2b X"001f", --2c drop, --2d drop, --2e RET, --2f : factorial ( n -- n! ) 1 2 ROT BEGIN 2DUP <= WHILE -ROT TUCK * SWAP 1+ ROT REPEAT 2DROP ;