Prev Problem
Next Problem

70. Universal Barrel Shifter

module univ_barrel8 (
    input  [7:0] x,
    input  [2:0] sh,    // 0..7
    input  [2:0] mode,  // see table below
    output reg [7:0] y
);
    // mode encodings
    localparam [2:0]
        M_PASS = 3'b000,
        M_LSL  = 3'b001,
        M_LSR  = 3'b010,
        M_ASR  = 3'b011,
        M_ROL  = 3'b100,
        M_ROR  = 3'b101;

    always @* begin
        case (mode)
            M_PASS: y = x;                                        // pass-through
            M_LSL : y = (x << sh) & 8'hFF;                        // logical left
            M_LSR : y = (x >> sh);                                // logical right
            M_ASR : y = $signed(x) >>> sh;                        // arithmetic right
            M_ROL : y = ((x << sh) | (x >> (8 - sh))) & 8'hFF;    // rotate left
            M_ROR : y = ((x >> sh) | (x << (8 - sh))) & 8'hFF;    // rotate right
            default: y = x;                                       // reserved → PASS
        endcase
    end
endmodule

💡Remember

  • Logical vs Arithmetic: >> shifts in 0s; >>> keeps the sign (use $signed(x) to ensure correct behavior).
  • Rotate = combine complementary shifts; mask with 8'hFF after left shifts to keep 8 bits.
  • Shifting by 0 or by the full width (e.g., x << 8) yields defined zeros in Verilog-2005; the expressions above handle all sh 0..7 without special cases.
  • Unknown mode values in hardware should be mapped to a safe behavior (here, PASS) rather than x to keep designs synthesizable.