Q5a:Serial two's complementer(Moore FSM)
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.
题目网站
假设我们这边输入的都是负数,不用管符号位的问题;即补码全部都是取反加1求得。
以上图为例,输入的左边为低位数据,右边为高位数据;即输入为00110100,则取反加1后得输出为11001100;
取反操作好进行,主要麻烦在加一的操作上,不知道进位到哪一位为止,此时我们用状态机来解决;若最前面的输入都是0的话,取反均为1,低位加1的时候一直进位,则输出都是0,直到输入有个1为止(取反加1不进位),这一阶段我们用一个状态S0来表示;后面阶段就将输入取反进行输出即可,因为进位链在S0状态已结束;
因为是摩尔型状态机,输出的结果与输入无关,仅与状态有关。所以我们这里用到3个状态。
module top_module (
input clk,
input areset,
input x,
output z
);
parameter S0 = 2'd0, S1 = 2'd1, S2 = 2'd2;
reg [1:0] current_state, next_state;
always @(*) begin
case(current_state)
S0: next_state = x ? S1 : S0;
S1: next_state = x ? S2 : S1;
S2: next_state = x ? S2 : S1;
endcase
end
always @(posedge clk or posedge areset) begin
if(areset)begin
current_state <= S0;
end
else begin
current_state <= next_state;
end
end
assign z = (current_state == S1);
endmodule