拼接运算符
本课属于 Coddy Verilog 学习旅程的“基础知识”单元。第 27 课,共 90 课。
拼接运算符 { } 会将多个信号、常量或表达式合并成一个更大的向量。每当你需要将多个位拼接起来组成更宽的值时,就可以使用它。
哪些值可以进行拼接
你可以拼接:
- 线网和寄存器:任意信号
- 常量:例如
4'b1010或8'hFF这样的数字
- 表达式:运算的结果,例如
a + b - 重复:多次重复一个值
所有拼接的值都必须具有固定且已知的宽度。
基本语法: {value1, value2, value3, ...} 结果的宽度是所有单个宽度之和。
示例
将两个 4 位值合并为 8 位:
reg [3:0] high, low;
reg [7:0] word;
word = {high, low}; // high 成为高 4 位,low 成为低 4 位与常量组合:
data = {4'b1010, 4'b0000}; // 8'b10100000合并两个以上:
full = {a, b, c, d}; // All widths add up重复
你可以使用 {n{value}} 多次重复一个值:
repeated = {4{4'b1010}}; // 16'b1010101010101010 (repeat 4 times)这在符号扩展中很有用:
signed_8bit = {{4{sign_bit}}, value_4bit};代码示例
module concatenation_demo;
reg [3:0] upper, lower;
reg [7:0] combined;
reg [11:0] repeated;
initial begin
upper = 4'b1010;
lower = 4'b1100;
combined = {upper, lower}; // 10101100
repeated = {3{4'b1010}}; // 101010101010
$display("{upper, lower} = %b", combined);
$display("{3{4'b1010}} = %b", repeated);
$finish;
end
endmodule输出:
{upper, lower} = 10101100
{3{4'b1010}} = 101010101010重要说明
- 顺序很重要:
{a, b}和{b, a}不同 - 所有部分都必须具有固定宽度(不能使用未指定宽度的数字)
- 赋值语句的左侧和右侧都可以使用拼接
挑战
为每项任务写出正确的拼接表达式。
要做什么:
- 将
a和b拼接成一个 8 位结果,并存入combine1 - 将
c、d和e拼接成一个 12 位结果,并存入combine2 - 将
f和两个g拼接成一个 12 位结果,并存入combine3
亲手试试
module concatenation_challenge;
reg [3:0] a, b;
reg [3:0] c, d, e;
reg [3:0] f, g;
reg [7:0] combine1;
reg [11:0] combine2, combine3;
initial begin
a = 4'b1010;
b = 4'b0101;
c = 4'b1111;
d = 4'b0000;
e = 4'b1100;
f = 4'b1001;
g = 4'b0110;
combine1 = ______; // Combine a and b into an 8-bit result
combine2 = ______; // Combine c, d, and e into a 12-bit result
combine3 = ______; // Combine f and two copies of g into a 12-bit result
$display("{a, b} = %b", combine1);
$display("{c, d, e} = %b", combine2);
$display("{f, g, g} = %b", combine3);
$finish;
end
endmodule这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Verilog 在线编译器