题解 | #非整数倍数据位宽转换8to12#
非整数倍数据位宽转换8to12
http://www.nowcoder.com/practice/11dfedff55fd4c24b7f696bed86190b1
`timescale 1ns/1ns
module width_8to12(
input clk ,
input rst_n ,
input valid_in ,
input [7:0] data_in ,
output reg valid_out,
output reg [11:0] data_out
);
reg [1:0] cnt;
reg [7:0] data;
always @ (posedge clk or negedge rst_n) begin
if (~rst_n) begin
cnt<=2'b0;
end
else if (valid_in)
cnt<=(cnt==2'd2)?0:cnt+2'd1;
else
cnt<=cnt;
end
always @ (posedge clk or negedge rst_n) begin
if (~rst_n) begin
valid_out<=1'd0;
end
else
valid_out<=(cnt==2'd1||cnt==2'd2)&&(valid_in);
end
always @ (posedge clk or negedge rst_n) begin
if (~rst_n) begin
data<=8'd0;
data_out<=12'd0;
end
else if (valid_in) begin
if (cnt==0) begin
data<=data_in;
data_out<=data_out;
end
if (cnt==1) begin
data<=data_in;
data_out<={data,data_in[7:4]};
end
if (cnt==2) begin
data<=data_in;
data_out<={data[3:0],data_in};
end
end
end
endmodule
module width_8to12(
input clk ,
input rst_n ,
input valid_in ,
input [7:0] data_in ,
output reg valid_out,
output reg [11:0] data_out
);
reg [1:0] cnt;
reg [7:0] data;
always @ (posedge clk or negedge rst_n) begin
if (~rst_n) begin
cnt<=2'b0;
end
else if (valid_in)
cnt<=(cnt==2'd2)?0:cnt+2'd1;
else
cnt<=cnt;
end
always @ (posedge clk or negedge rst_n) begin
if (~rst_n) begin
valid_out<=1'd0;
end
else
valid_out<=(cnt==2'd1||cnt==2'd2)&&(valid_in);
end
always @ (posedge clk or negedge rst_n) begin
if (~rst_n) begin
data<=8'd0;
data_out<=12'd0;
end
else if (valid_in) begin
if (cnt==0) begin
data<=data_in;
data_out<=data_out;
end
if (cnt==1) begin
data<=data_in;
data_out<={data,data_in[7:4]};
end
if (cnt==2) begin
data<=data_in;
data_out<={data[3:0],data_in};
end
end
end
endmodule