generate blocks let you write structural or repetitive logic parametrically, so the same module works for any width without hand-writing every bit. Combined with a module parameter, this makes truly reusable hardware building blocks.
Build a parameterized circuit top_module with a parameter WIDTH (default 8), a WIDTH-bit input in, and a WIDTH-bit output out. For every bit position i, out[i] should equal in[i] XORed with its neighbor “to the right”, wrapping around: in[(i+1) mod WIDTH]. This forms a “ring” since bit WIDTH-1’s neighbor wraps back around to bit 0.
Interface
| Signal | Direction | Width | Description |
|---|---|---|---|
in |
input | WIDTH |
Input vector |
out |
output | WIDTH |
out[i] = in[i] ^ in[(i+1) % WIDTH] |
Example (WIDTH = 4)
If in = 4'b1010:
out[0] = in[0] ^ in[1] = 0 ^ 1 = 1out[1] = in[1] ^ in[2] = 1 ^ 0 = 1out[2] = in[2] ^ in[3] = 0 ^ 1 = 1out[3] = in[3] ^ in[0] = 1 ^ 0 = 1
So out = 4'b1111.
Notes
- Declare a
genvar i;before thegenerate forloop; genvars only exist at elaboration time and are used purely to unroll the loop. - Give the generated block a label (e.g.
begin : xor_ring) — required by many tools for generate blocks containing more than one statement, and good practice regardless. - The modulo operator
%computes the wraparound neighbor index;(WIDTH-1 + 1) % WIDTHcorrectly evaluates to0.