ASSEMBLY / CHAPTER 06

Extracting and replacing packed bit fields

Master

Update one bit range while preserving neighboring fields.

By the end of this chapter

  • Shift and mask for extraction
  • Clear a field before replacement
  • Constrain replacement values to their field width

The idea

A packed field occupies a specified range of bits within a register or memory word. To extract bits four through seven, shift a copy right by four and mask its low four bits. Copying first preserves the original word. State the width and signedness of the field; this example treats it as an unsigned four-bit value.

Replacing a field is different from setting selected bits. Clear all bits of the destination field, mask the replacement to its permitted width, shift it into position, and combine with OR. Without clearing first, old one bits can survive a replacement intended to contain zeros. Without constraining the replacement, high bits can spill into neighboring fields. All examples use small in-range shift counts and conceptual register traces.

Assembly example
; Extract bits 4..7 from EAX without changing EAX.
mov eax, 0xAB
mov edx, eax
shr edx, 4
and edx, 0x0F
Result
EAX = 0xAB; EDX = 10.

Shifting moves the upper nibble into the low position, and masking removes unrelated bits.

Try it yourself

Replace bits 8..11 with an unsigned four-bit value while preserving every other bit.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which mask clears only bits 4 through 7 of a 32-bit value?