Medium · Combinational Logic · Parameterization & Generate
Implement a parameterized barrel rotator: rotate a WIDTH-bit word left or right by 0 … WIDTH-1 positions in a single combinational step.
A rotate is a shift in which the bits that fall off one end re-enter at the other end; nothing is lost and nothing is filled with zeros.
module barrel_rotator #(
parameter int WIDTH = 8
) (
input logic [WIDTH-1:0] din,
input logic [$clog2(WIDTH)-1:0] amt,
input logic dir,
output logic [WIDTH-1:0] dout
);
| Name | Kind | Width | Meaning |
|---|---|---|---|
WIDTH | parameter | — | Word width, any power of two ≥ 2 (2, 4, 8, 16, …). Default 8. |
din | input | WIDTH | Word to rotate. |
amt | input | $clog2(WIDTH) | Rotate amount, unsigned, 0 … WIDTH-1. |
dir | input | 1 | 0 = rotate left (toward the MSB), 1 = rotate right (toward the LSB). |
dout | output | WIDTH | Rotated word. |
For every bit position i (with indices taken modulo WIDTH):
dir = 0): dout[(i + amt) % WIDTH] = din[i]dir = 1): dout[i] = din[(i + amt) % WIDTH]With amt = 0 the output equals the input in both directions. The circuit is purely combinational.
din | amt | dir | dout |
|---|---|---|---|
1001_0110 | 0 | 0 (left) | 1001_0110 |
1001_0110 | 1 | 0 (left) | 0010_1101 |
1001_0110 | 3 | 0 (left) | 1011_0100 |
1001_0110 | 1 | 1 (right) | 0100_1011 |
1001_0110 | 3 | 1 (right) | 1101_0010 |
1000_0000 | 7 | 0 (left) | 0100_0000 |
WIDTH is any power of two ≥ 2. The hidden tests instantiateyour module at the default WIDTH = 8 and at other powers of two (including the smallest), so do not hard-code 8 anywhere except the parameter default. The visible examples use WIDTH = 8 only.
{din, din}, shift that 2*WIDTH-bitvalue, then take the right half. Another approach is a for loop that assigns each output bit from the input bit it comes from.
$clog2(WIDTH) stages of 2:1muxes; stage k rotates by 2**k when amt[k] is set. You may build it that way with a generate loop, but it is not required.
Sign up free to solve Parameterized Barrel Rotator in your browser.