HDLBits Exams/ece241 2014 q5a
1.题目
题目链接:https://hdlbits.01xz.net/wiki/Exams/ece241_2014_q5a
You are to design a one-input one-output serial 2’s complementer Moore state machine. The input (x) is a series of bits (one per clock cycle) beginning with the least-significant bit of the number, and the output (Z) is the 2’s complement of the input. The machine will accept input numbers of arbitrary length. The circuit requires an asynchronous reset. The conversion begins when Reset is released and stops when Reset is asserted.
题目大意为用Moore状态机输出二进制数据的补码。
2.思路
补码规则:正数为原码,负数为原码取反加一。
本题中,当输入全为0时,认为是正数,z直接输出。当x出现第一位1时,认为输入二进制数据为负数,此时补码扔为输入本身,例如1_0000_0000补码仍为1_0000_0000。出现第一位1之后的输入位,根据补码规则,应取反,例如1001_0000_0000的补码为1111_0000_0000。
根据上述规则,可以确定三个状态:
3.代码
module top_module (
input clk,
input areset,
input x,
output z
);
reg [1:0] state,next;
parameter s0=0,s1=1,s2=2;
always @(posedge clk or posedge areset) begin
if(areset) begin state<=s0; end
else state<=next;
end
always @(*) begin
case(state)
s0: begin next=x?s1:s0; end
s1: begin next=x?s2:s1; end
s2: begin next=x?s2:s1; end
endcase
end
assign z=state==s1;
endmodule