[Nand2Tetris] Making VM translator: Logical instructions

조현호_ChoHyeonHo·2025년 1월 2일

Debug: x-y

if command == "sub":
            # x-y
            # decrement SP
            asm_tmp += self.decrement_SP()
            
            # save M into D register. D is y
            asm_tmp += "D=M\n"
            
            # decrement SP again
            asm_tmp += self.decrement_SP()
            
            # save sub at M register
            asm_tmp +=  "M=D-M\n"
            
            # increment SP
            asm_tmp += self.increment_SP()
            

asm_tmp += self.decrement_SP(): decrement stack pointer
asm_tmp += "D=M\n": Save y value into the D register
asm_tmp += self.decrement_SP(): decrement stack pointer again to focus x
asm_tmp += "M=D-M\n": Got ya. so the M is x, but i'm subtracting it from y so this results y-x, not x-y.

Making bit operators

AND

  1. So we already have saved the binary digits in the memory.
  2. Then how can we get the 'and' operated value of two binary digits? do we have asm code?

    Yes. We have bit operators like &,|, and every arithmatic operators in asm level.

So we can simply use it like following code.

if command == 'and':
            # x And y
            asm_tmp = '// AND operator\n'
            asm_tmp += self.decrement_SP()
            # save M into D register
            asm_tmp += "D=M\n"
            # decrement again
            asm_tmp += self.decrement_SP()
            # do asm operation.
            asm_tmp += "M=D&M\n"
            asm_tmp += self.increment_SP()

OR

just switch & into |

NOT

Then, what's the difference between neg and not operation? Take a look at the specs of VM.

neg(2) = -2
not(2) = -3

00000010  (2)
--------  (not op)
11111101  (-3)

So it can be implemented using !M operator in asmbler spec.

        if command == 'not':
            # NOT y
            asm_tmp = '// NOT operator\n'
            asm_tmp += self.decrement_SP()
            # do asm operation.
            asm_tmp += "M=!M\n"
            asm_tmp += self.increment_SP()
profile
Behold the rabbit hole

0개의 댓글