HDLBits: Serial two‘s complementer

一、前言

菜鸟总结刷hblbits的心得体会,有错误还请指正!

二、Moore FSM

1、原题目

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.

2、设计思路

简单来说是设计一个Morre FSM 将输入转换为它的补码形式输出。

注意:

(1)默认输入x是负数,且无符号位。

(2)输出比输入要晚一个时钟周期。

(3)补码的另一种理解:从低位到高位(不包括最高位),遇到第一个1之后,其余的高位全部取反,最后再加上最高位,即可得到补码。如例子中,输入为011_0100,输出为100_1100

由以上思路设计的状态机如下图所示:

3、我的代码

module top_module (
    input clk,
    input areset,
    input x,
    output z
); 
	parameter S0 = 4'b0001,S1=4'b0010,S2=4'b0100,S3=4'b1000;
    reg [3:0] state,next_state;
    
    always @(*) begin
        case(state) 
            S0: next_state = x ? S1 : S0;
            S1: next_state = x ? S2 : S3;
            S2: next_state = x ? S2 : S3;
            S3: next_state = x ? S2 : S3;
        endcase 
    end
    
    always @(posedge clk or posedge areset) begin
        if(areset)
            state <= S0;
        else
            state <= next_state;
    end
    
    always @(*) begin
        case(state)
            S0: z = 1'b0;
            S1: z = 1'b1;
            S2: z = 1'b0;
            S3: z = 1'b1;
        endcase
    end
endmodule

三、Mealy FSM

1、原题目

2、设计思路

思路跟上面是一样的,只不过要将上面的Morre FSM改为Mealy FSM,得到新的状态机如下图所示:

3、我的代码

module top_module (
    input clk,
    input areset,
    input x,
    output z
); 
	parameter S0=2'b01,S1=2'b10;
    reg [1:0] state,next_state;
    
//state transitiion logic
    always @(*) begin
        case(state)
            S0: next_state = x ? S1 : S0;
            S1: next_state = S1;
        endcase
    end
    
//state flip_flops
    always @(posedge clk or posedge areset) begin
        if(areset)
            state <= S0;
        else 
            state <= next_state;
    end
    
//output logic
    assign z = (state==S0) ? x : (!x);
endmodule

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值