Search code examples
c++assemblyarmthumb

inquiry in designing my Arm simulator function representing format 1


The following function represents format 1 in ARM Thumb. I don't understand the part of using AND(&) after shifting in each declaration of the fields of the formats and why did we use these numbers after AND? format 1 representation in ARM architecture

int simulate(unsigned short instr)
{
    unsigned char fmt, op, offset5, rd, rs, offset3, rn;

    fmt = (instr) >> 13;

    switch(fmt){
        case 0:             // format 1/2
            op = (instr >> 11) & 3;
            rd = instr & 7;
            rs = (instr >>  3) & 7;
            offset5 = (instr >> 6) & 0x1F;
            if(op!=3) {     // format 1
                /*
                switch(op){
                    case 0: printf("lsl\tr%d, r%d, #%d\n", rd, rs, offset5); break;
                    case 1: printf("lsr\tr%d, r%d, #%d\n", rd, rs, offset5); break;
                    case 2: printf("asr\tr%d, r%d, #%d\n", rd, rs, offset5); break;
                
                }*/
 

Solution

  • For something like op, it is supposed to be 2 bits long, but it's at some offset into your instruction. So you need to get the op bits shifted all the way to the least significant position, then remove any remaining bits.

    The shift moves the bits to the least significant bit position in your op unsigned char, and ANDing that with 3 (which is 11 in binary, meaning only keep the 2 least significant bits) gets rid of anything in the higher bit positions (for op those should be all 0s, but for something like offset5 it would not be).

    It's the same for each of the other parts of the instruction. offset5 is 5 bits long, so we need 11111 in binary, which is 0x1F, and so on.