Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can anyone explain to me what this shifting means under this circumstance: uint16_t register0 = (instruction >> 9) & 0x7

I’m trying to write a VM (LC-3), and on this ADD instruction I encountered this statement. Basically the "register0" is the DR register, but I don’t really understand what is actually shifting and why 9. Also the AND operator with the 0x7 value.

|15|14|13|12|11|10|9|8|7|6|5|4|3|2|1|0|
|    0001   |  DR   | SR1 |0| 00| SR2 |

Could anyone please explain it to me in detail?

ADD {
    /* destination register (DR) */
    uint16_t r0 = (instr >> 9) & 0x7;
    /* first operand (SR1) */
    uint16_t r1 = (instr >> 6) & 0x7;
    /* whether we are in immediate mode */
    uint16_t imm_flag = (instr >> 5) & 0x1;
    if (imm_flag) {
        uint16_t imm5 = sign_extend(instr & 0x1F, 5);
        reg[r0] = reg[r1] + imm5;
    } else {
        uint16_t r2 = instr & 0x7;
        reg[r0] = reg[r1] + reg[r2];
    }
    update_flags(r0);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What it’s doing is isolating the 3 bits that represent the DR register so they become a standalone number.

Let’s say the entire sequence looks like this:

1110101101101011
    ^^^
     DR

Shifting 9 bits right gives this:

1110101

and & 0x7 (bitwise AND) isolates the 3 lowest bits:

101

Similar operations are performed to isolate the values of SR1 and the immediate mode flag. Depending on that flag, SR2 may also be required, but as it’s already in the lowest 3 bits, no shifting is needed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading