BitShifts
To extract a field from an integer called, for instance, "instruction", and place it into the variable "field":
1) Three-bit field from bit 12 to bit 14, assuming that the first bit is bit 0.
field = (instruction >> 12) & 0x7;
This shifts the bits in "instruction" down by 12 bits, then uses a mask to zero out everything but the bits in the lowest three places (bits 0-2). After the shift, bits 12-14 are in locations 0-2.
2) Bits 8-11:
field = (instruction >> 8) & 0xf;
3)Bits 2-7:
field = (instruction >> 2) & 0x3f;
Bits 13-15:
field = (instruction >> 13) & 0x7;
To insert a field into the integer called "instruction":
3-bit quantity to bits 10-12.
instruction = (field & 0x7) << 10;
The and ensures that "field" contains a 3-bit number (by zeroing out any other bits), and the shift puts the three-bit field into place. The variable
"instruction" now contains only the three-bit field now in bits 10-12. To construct instructions out of many fields:
Suppose we have a 3-bit opcode stored in the variable op, we have a 3-bit register stored in the variable r1, and we have another 3-bit register stored in the
variable r2. Say we want them (respectively) in bits 15-13, 12-10, and 9-7. We would build up the instruction as follows:
field = (instruction >> 8) & 0xf;
instruction = ((op & 0x7) << 13) | ((r1 & 0x7) << 10) | ((r2 & 0x7) << 7);
The ands ensure that each variable is only three bits wide, by masking out all other bits. The left-shifts put the values into place, according to the desired location.
Since there is no overlap between the fields (we have ensured this by masking out any possible extra bits), the ors simply concatenate the fields together.
(Taken from http://www.ee.umd.edu/courses/enee350h.F97/)
|