01Implementation
Swap the halves of a byte
Problem
Intended behavior. nibble_swap receives an 8-bit vector value and drives
an 8-bit swapped. Bits [7:4] of the input must appear in bits [3:0] of the
output, and bits [3:0] of the input must appear in bits [7:4]. With
8'hA5 on the input, swapped reads 8'h5A.
Current behavior. The starter compiles and runs, but its single assign
copies value unchanged, so every printed line shows the same hex digits on both
sides.
Your task. Replace the right-hand side of the marked assign so that the two
4-bit halves trade places. Keep the port names and widths, and leave the public
testbench below the marker untouched.
Read and predict
A declaration such as [7:0] numbers the bits of a vector from 7 at the left to
0 at the right, and each hex digit of an 8-bit value covers exactly four of
those bits. Before editing, write down what the three printed rows should show
for 8'hA5, 8'h0F, and 8'h3C once the halves are exchanged. Then run the
starter and compare its unchanged swapped values with your predicted outputs.
Fix and explain
The only line to change is the assign under the TODO. Build the new
right-hand side from the two halves of value; the vectors example in the
Basic Syntax chapter uses every operator you need. Run again: every swapped value
should now show the two hex digits of value in reverse order. Finally, explain
why the fix adds no logic gates at all, only a different routing of the same
eight wires.
Completion check
- Every one of the 256 possible inputs produces its exchanged halves, not only the three values the public testbench prints.
- No bit is lost or duplicated: the high nibble of the output depends only on the low nibble of the input, and the reverse.
- The module stays purely combinational with the same ports.
Progressive hints
Hint 1
A shift moves bits toward one end and fills the other end with zeros. Shifting alone keeps only one of the two halves; you need both at once.
Hint 2
A range written after a vector name, such as value[7:4], selects just those
bits as a 4-bit value. Name the two halves that way first.
Hint 3
Braces join smaller vectors into one wider vector, with the first item becoming the most significant bits. Two 4-bit pieces joined this way form exactly eight bits.
Transfer experiment
Predict the output for 8'h12 and for 8'hFF before trying them. Then consider
a 16-bit vector: which ranges would you join to swap its two bytes, and why
does the order inside the braces decide which byte lands on top?