Verilog刷题[hdlbits] :Module addsub

题目:Module addsub

An adder-subtractor can be built from an adder by optionally negating one of the inputs, which is equivalent to inverting the input then adding 1. The net result is a circuit that can do two operations: (a + b + 0) and (a + ~b + 1). See Wikipedia if you want a more detailed explanation of how this circuit works.

  • 加法器-减法器可以由加法器通过选择性地对其中一个输入求反来构建,这相当于对输入求反然后加1。最终结果是一个可以进行两个运算的电路:(a+b+0)和(a+~b+1)。如果你想更详细地解释这个电路是如何工作的,请参阅维基百科。

Build the adder-subtractor below.

  • 构建下面的加减法器。

You are provided with a 16-bit adder module, which you need to instantiate twice:

  • 为您提供了一个16位加法器模块,您需要实例化两次:
    module add16 ( input15:0 a, input15:0 b, input cin, output15:0 sum, output cout );

Use a 32-bit wide XOR gate to invert the b input whenever sub is 1. (This can also be viewed as b31:0 XORed with sub replicated 32 times. See replication operator.). Also connect the sub input to the carry-in of the adder.

  • 每当sub为1时,使用32位宽的XOR门来反转b输入。(这也可以被视为b31:0与子复制进行32次异或。请参阅复制运算符。)也可以将子输入连接到加法器的进位。

该题目实现较为简单,题目中也给出了可以通过前面章节学习的复制将sub进行扩展,但该题目需要理解为什么通过异或与设置cin位为sub就能够将加法器改造为减法器。B站Up主视频讲解了计算机能够通过补码完成加减法运算。

因此,在进行减法运算时,需要将被减数b的补码变为-b的补码,视频中讲解了可以将每一位均取反再加+1。当sub为1,完成位扩展后变为32个1。此时,再与b进行异或操作(不相同为1,相同为0),即可完成取反,在结合sub的进位即可完成b的补码变为-b的补码。通过a+(-b)的补码完成取反操作。

同时,当sub为0是,b异或后不变,且进位cin为0,与原来的加法器一样。

objectivec 复制代码
module top_module(
    input [31:0] a,
    input [31:0] b,
    input sub,
    output [31:0] sum
);
 	//进位信号
    wire cout;
    wire [31:0] b_xor;
    
    assign b_xor = {32{sub}} ^ b;
    
	//低16位相加
	add16 add16_init_0( 
        .a(a[15:0]), 
        .b(b_xor[15:0]),
        .cin(sub), 
        .sum(sum[15:0]), 
        .cout(cout) 
    );
    
    //高16位相加
	add16 add16_init_2( 
        .a(a[31:16]), 
        .b(b_xor[31:16]),
        .cin(cout), 
        .sum(sum[31:16]),
        .cout() 
    );

endmodule
相关推荐
FPGA小迷弟5 小时前
FPGA开发Vivado Block Design/Vitis/SDK/xlinx/开发教程,保姆级别,一看就会!
网络协议·tcp/ip·fpga开发·verilog·fpga
FPGA小迷弟6 小时前
基于FPGA实现智能网卡的概念,什么是智能网卡
网络协议·tcp/ip·fpga开发·verilog·fpga
好焊孙辉8 小时前
螺柱焊机哪家质量好
python·fpga开发
XMAIPC_Robot13 小时前
基于 i.MX95 平台在新一代工业控制器中的应用 — 工业车载平板、半导体设备主控方案解析
arm开发·人工智能·机器学习·fpga开发·rk3588+fpga·i.mx95
szxinmai主板定制专家13 小时前
基于 AM62x + Artix-7 的低功耗 ARM+FPGA 平台在轨道交通车门控制中的应用
arm开发·人工智能·fpga开发·zynq·am62x
幻智星科技13 小时前
我砍掉了FPGA里的ARM核项目反而提前交付了
arm开发·网络协议·fpga开发·硬件架构
逐光者93313 小时前
Verilog 三段式状态机:原理、模板与实战
fpga开发
XMAIPC_Robot14 小时前
NXP i.MX95 + FPGA 异构计算平台 — 工业多域融合 AI 加速嵌入式控制解决方案
人工智能·分布式·fpga开发·能源·rk3576+fpga
FPGA小迷弟1 天前
用 Claude Code 重构遗留系统:从评估到落地的完整指南
fpga开发·dsp开发·fpga·1024程序员节·sdr·无线电
专注仿真1 天前
Vivado FPGA 开发实战项目:从入门到上板
fpga开发