Extracting fields with Shift/Mask
- Shift the field down to the least significant bit of the word.
- Mask out all the bits that are not part of the field.
Extracting fields with Shift/Mask Example
int hour = dtv.b03 & 0x3F;
int second = (dtv.bo3 >> 12) & 0x3F;
int month = dtv.b45 & 0xF;Hour and second are 6 bit fields. Month is a 4 bit field. Second starts in bit 12. Hour and month start in bit 0.
Assigning Value to Bit Field
- Clear the value in the existing field
- Bits we want to change their value. Not touch anything else.
- Reason: we need all the bits to be 0 where we want to put the results
- Clear the extraneous (or sign) bits in the value to assign
- Make sure the value is within the range
- If its outside we want to clean it up
- Make sure we don't have more than 4 bits
- Shift the value over to the starting position
- 0th bit of value lines up with starting position (low bit position) of where we're going
ORthe value into the field
Example
// clear second
dtv.b03 &= 0xFFFC0FFF;
// 37 will fit into 6 bits - nothing extra to zap
dtv.b03 |= (37 << 12); // shift over and or in