将字符串常量转换为虚拟机代码
Translating String Constants to Virtual Machine Code
我有一个学校项目,将 jack 程序翻译成 vm 代码。我们得到了一些模糊的指示,然后自己去做。
我在将字符串常量转换为 vm 代码时遇到了问题。
假设程序中有如下命令:
do Output.printString("Hello world!")
翻译应该是这样的:
push SOMETHING (I don't know what to put here)
call Output.printString 1
如何将字符串翻译成虚拟机?
谢谢!
这是我的发现:
有两个函数用于创建字符串。 String.new
和 String.appendChar
。
要创建一个字符串,首先调用 String.new
并将字符串的长度作为参数。然后,为每个字符调用 String.appendChar
,将当前字符的 ascii 值作为函数的参数。
因此,例如,要创建字符串 "Hello World"
:
push constant 11 //this is the length of the word
call String.new 1
push constant 72 //ascii of h
call String.appendChar 2
//continue this for each character in the word
...
call Output.printString 1 //prints the string that we created
我有一个学校项目,将 jack 程序翻译成 vm 代码。我们得到了一些模糊的指示,然后自己去做。
我在将字符串常量转换为 vm 代码时遇到了问题。
假设程序中有如下命令:
do Output.printString("Hello world!")
翻译应该是这样的:
push SOMETHING (I don't know what to put here)
call Output.printString 1
如何将字符串翻译成虚拟机?
谢谢!
这是我的发现:
有两个函数用于创建字符串。 String.new
和 String.appendChar
。
要创建一个字符串,首先调用 String.new
并将字符串的长度作为参数。然后,为每个字符调用 String.appendChar
,将当前字符的 ascii 值作为函数的参数。
因此,例如,要创建字符串 "Hello World"
:
push constant 11 //this is the length of the word
call String.new 1
push constant 72 //ascii of h
call String.appendChar 2
//continue this for each character in the word
...
call Output.printString 1 //prints the string that we created