assemblynand2tetris

Initializing an array in Hack Assembly Code


What is the syntax for declaring initialized data, such as:

ex. int [] arr = {1, 2, 3, 4, 5}

"hello world\n"


Solution

  • The Hack assembly language has no facility for doing this directly, since it only assembles program instructions, and the program memory is read-only and not readable by Hack machine instructions, other than the degenerate case of the load constant operation.

    Thus, what you have to do is write code that initializes your ram, using a sequence of load constant/store operations. This is made a little more tricky because you can only load 15-bit constants.

    When I was faced with this issue I wrote a python script to generate the assembly code I needed. Here is a python code snippet that generates code to store an arbitrary value "word" into the memory location "base" that may prove helpful to you.

    if word >= 32768:
        if word == 65535:
            print "\t@" + "{:05}".format(base) + "\t\t// " + str(word)
            print "\tM = -1"
        else:
            print "\tD = -1\t\t// " + str(word)
            print "\t@" + "{:05}".format(65535-word)
            print "\tD = D - A"
            print "\t@" + "{:05}".format(base)
            print "\tM = D"
    else:
        if word == 0:
            print "\t@" + "{:05}".format(base) + "\t\t// " + str(word)
            print "\tM = 0"
        else:
            print "\t@" + "{:05}".format(word) + "\t\t// " + str(word)
            print "\tD = A"
            print "\t@" + "{:05}".format(base)
            print "\tM = D"
    
    base += 1