Skip to content
code0.HDL

03Verification

Add a signed offset

Problem

Intended behavior. SignedOffset moves an 8-bit address base by a signed 4-bit delta between −8 and 7. addr is base + delta, wrapping within eight bits: 250 + 7 gives 1 and 3 + (-8) gives 251.

Current behavior. The starter compiles and positive offsets work. Every negative offset moves the address forward: 100 + (-1) prints 115.

Task. Find why a negative delta is read as a large positive number and fix the addr connection. Keep all three port types.

Read the starter

The ports already say what each value means: base is unsigned and delta is SInt. Follow delta = -1 through the single connection. Write its four bits, then ask what asUInt turns them into and how the addition widens that 4-bit value to meet the 8-bit base.

Predict before running

The public run prints four rows: (100, 3), (100, -1), (100, -8), and (250, 7). Predict the starter's output for each, then the correct output. Mark which rows the defect touches.

Run and explain

The starter prints 103, 115, 108, and 1. The two positive rows are right, including the wrap at 250. For −1 the bits are 1111; once asUInt reads them as 15, the widening to eight bits pads with zeros, so the sum is 100 + 15. For −8, 1000 becomes 8 and the sum is 108. The bits were never wrong. The reading was changed to unsigned before the value was widened, so the extension used zeros instead of copies of the sign bit. Correct output is 103, 99, 92, and 1.

Completion check

  • Every base from 0 to 255 combined with every delta from −8 to 7 gives base + delta modulo 256.
  • Wrapping works in both directions, past 255 and below 0.
  • Matching the printed offsets alone does not count; −2 through −7 must work too.

Progressive hints

Hint 1

1111 means −1 only while it is read as SInt. Extension depends on the type at the moment a value is widened: zeros for UInt, sign copies for SInt.

Hint 2

Let the widening happen while delta is still signed. If both operands of the addition are SInt, the narrower one is sign-extended. A cast changes no bits, so reinterpreting base does not change the result modulo 256. Convert back to unsigned at the end.

Concept

asUInt and asSInt reinterpret bits without extending them. When one of these conversions and a width change meet in one expression, their order decides the value, as the data types chapter showed with widebits.

Transfer experiment

Read base = 200 as an 8-bit SInt: it is −56. Explain why doing the addition in signed arithmetic still produces the right unsigned address for 200 + (-8) and for 250 + 7.

Review this concept
Ready

CheerpJ runs Chisel in your browser. A cold Run downloads about 14.5 MB of Java and 47 MB of JARs. Compilation can take a minute. Licenses

Main.scala