Root Work Programming Misc Hex/Bin/Dec Conversions and Methods

   BitMasks
        #Bits   Bit Pattern     Hex Number
        1       1               0x1
        2       11              0x3
        3       111             0x7
        4       1111            0xf
        5       11111           0x1f
        6       111111          0x3f
        7       1111111         0x7f
        8       11111111        0xff
        9       111111111       0x1ff
        10      1111111111      0x3ff
        11      11111111111     0x7ff
        12      111111111111    0xfff


	0 and 0 = 0
	0 and 1 = 0
	1 and 0 = 0
	1 and 1 = 1

	0 or 0 = 0
	0 or 1 = 1
	1 or 0 = 1
	1 or 1 = 1

	0 xor 0 = 0
	0 xor 1 = 1
	1 xor 0 = 1
	1 xor 1 = 0

 Bin  Dec  Hex 
000
111
1022
1133
10044
10155
11066
11177
100088
100199
101010A
101111B
110012C
110113D
111014E
111115F
100001610
100011711
etcetcetc
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/)