Hack codes

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

Hack codes

Gothem
How to do the codes: x = *ptr++ with hack language;
Reply | Threaded
Open this post in threaded view
|

Re: Hack codes

WBahn
Administrator
This post was updated on .
EDIT: My original response to this had an error. This is the corrected response:

This is a notation from the C language (and others). It's important to apply the operations according to the defined operator precedence, which state that post increment (the ++) has priority over the indiration (the *), so this is interpretted as:

val = *(ptr++)

This statement has two side effects in that it changes the value in both 'val' and 'ptr'.

The expression (ptr++) increments the value stored in ptr, but evaluates to the original value.

Therefore, these can be split apart as follows:

val = *ptr
ptr = ptr + 1

Since the original post is more than five years old, it's safe to give a complete answer.

If we implement this as two separate statements, we have:

For the first statement, we need to get the value stored in ptr and use that as an address, retrieve the value stored there, and then store that value in val:

//val = *ptr
@ptr
A = M
D = M
@val
M = D

For the second statement, we just need to get the address of ptr into the A register and increment the value stored in that register:

//ptr = ptr + 1
@ptr
M = M+1

NOTE: I haven't tested this code, just came up with it on the fly and it's been over a year since I've even looked at Hack, so don't rely on this without verifying it.
Reply | Threaded
Open this post in threaded view
|

Re: Hack codes

FrisbeeChaser
In reply to this post by Gothem
This one is C++ language grammar. The line contains 3 operations:
1. dereference: val = *ptr;
2.  increment modification: ptr = ptr + 1;
3. assignment:  x = val

Could write assembly code for the above 3 operations, then translate the assembly code to hack binary code.