HDLbits - circuits- Combinational Logic 答题记录。区别于题目常见答案

Basic Gates - Gatesc 题目描述

原题目:

You are given a four-bit input vector in[3:0]. We want to know some relationships between each bit and its neighbour:

out_both: Each bit of this output vector should indicate whether both the corresponding input bit and its neighbour to the left (higher index) are ‘1’. For example, out_both[2] should indicate if in[2] and in[3] are both 1. Since in[3] has no neighbour to the left, the answer is obvious so we don’t need to know out_both[3].
out_any: Each bit of this output vector should indicate whether any of the corresponding input bit and its neighbour to the right are ‘1’. For example, out_any[2] should indicate if either in[2] or in[1] are 1. Since in[0] has no neighbour to the right, the answer is obvious so we don’t need to know out_any[0].
out_different: Each bit of this output vector should indicate whether the corresponding input bit is different from its neighbour to the left. For example, out_different[2] should indicate if in[2] is different from in[3]. For this part, treat the vector as wrapping around, so in[3]'s neighbour to the left is in[0].

题目翻译:

输入一个4位的输入向量in[3:0],输出每个比特和它相邻比特之间的一些关系;
out_both:这个输出向量的每一位应该表示对应的输入位和它左边的比特位(左边比特具有更高的索引)是否均为“1”。举例说明,out_both[2]应该指示出in[2]和in[3]是否均为1。
out_any:这个输出向量的每一位都应该表示相应的输入位和它右边的比特位是否存在“1”。
out_different:这个输出向量的每一位都应该表明相应的输入位是否与其左边的比特位不同。

解题思路:

可以使用for循环,遍历输入向量in的每一位,进行向左取与&、向右取或|、向左取异或^ 。
提取输入向量in 的长度j,作为循环次数,由于out_both只需要取到in的第j - 1位(i[j - 2]),循环只需要到j - 2;

代码如下:

module top_module( 
    input [3:0] in,
    output [2:0] out_both,
    output [3:1] out_any,
    output [3:0] out_different );

    integer i,j;
always@(*) begin
    out_both = 3'b0;
	out_any = 3'b0;
	out_different = 4'b0;
    j = $bits(in);
    
    for(i=0; i<j-1 ; i++)begin
        out_both[i] = in[i] & in[i+1];
        out_any[i+1] = in[i] | in[i+1];
        out_different[i] = in[i] ^ in[i +1];
    end
    out_different[j-1] = in[j-1] ^ in[0]; 
    end

endmodule

第二题,输入向量in长度增加到100时,代码通用;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值