Digital Logic
Barrel Shifter
A combinational circuit that can shift or rotate data by any number of positions in a single cycle.
Detailed Explanation
Unlike a simple shift register that shifts one position per clock, a barrel shifter uses layers of multiplexers to shift by 2^n positions at each stage. An 8-bit barrel shifter uses three mux layers (shift by 4, 2, 1) controlled by the shift amount's binary representation.
Barrel shifters support logical shifts (fill with zeros), arithmetic shifts (preserve sign), and rotations (wrap bits around). They're essential for implementing variable shift instructions efficiently.
Code Example
systemverilog
module barrel_shifter #(parameter N = 8) (
input logic [N-1:0] data_i,
input logic [$clog2(N)-1:0] shamt_i,
input logic left_i, // 1=left, 0=right
output logic [N-1:0] data_o
);
logic [N-1:0] stage [0:$clog2(N)];
assign stage[0] = data_i;
genvar i;
generate
for (i = 0; i < $clog2(N); i++) begin
assign stage[i+1] = shamt_i[i] ?
(left_i ? {stage[i][N-1-(2**i):0], {(2**i){1'b0}}} :
{{(2**i){1'b0}}, stage[i][N-1:2**i]}) :
stage[i];
end
endgenerate
assign data_o = stage[$clog2(N)];
endmodule