Operators and Signed Expressions
Operators
Blocking vs. Non-Blocking Assignments
Blocking (
=): Executes immediately, sequential.a = b; c = a; // c gets new aNon-blocking (
<=): Updates scheduled, parallel.a <= b; c <= a; // c gets old a- Guideline:
- Use
=in combinational always blocks. - Use
<=in sequential (clocked) always blocks.
- Use
Arithmetic
+, -, *, /, %
- Operands default to unsigned unless
signed. - Division by zero →
x.
reg signed [3:0] x = -3, y = 2;
assign z = x / y; // result = -1
Sign Operators
- Unary
+,- - Applies sign extension when needed.
Relational
<, <=, >, >=
- Result:
1or0. - If any operand has
x/z→ result =x.
Equality/Inequality
==,!=→ logical compare,x/z→x.===,!==→ case equality (checksx/ztoo).
if (a === 1'bx) $display("a is unknown");
Logical Comparison
&&, ||, !
- Treats any
x/zas unknown (x).
Bitwise Logical
&, |, ^, ~^
- Operates bit-by-bit.
assign y = a ^ b; // XOR
Shift
<<,>>→ logical shift.<<<,>>>→ arithmetic shift (preserve sign).
reg signed [7:0] a = -4;
assign b = a >>> 1; // arithmetic shift right → -2
Concatenation / Replication
assign x = {a, b}; // concat
assign y = {4{1’b1}}; // replicate → 1111
Reduction
Applies operator across all bits: &a, |a, ^a, ~&a, etc.
assign parity = ^data; // XOR reduction (parity bit)
Conditional (?:)
assign out = sel ? a : b;
- The conditional (
?:) operator is an inline if–else in an expression:y = sel ? a : b;sel=1→ use the then value;sel=0→ use the else value.
- Crucial with
sel = x/z: Verilog evaluates both branches and merges bit-by-bit:- If branch values are identical → result is that value.
- If they differ → result is
x. - Examples:
(1’bx) ? 4’b1111 : 4’b1111→1111(1’bx) ? 4’b1111 : 4’b0000→xxxx
Signed expressions
$signed(expression)
- Converts
expressioninto a signed expression of the same bit-width. - Interprets MSB as the sign bit (two’s complement).
Example:
reg [3:0] a = 4'b1000; // 8 (unsigned) $display("%0d", $signed(a)); // -8
$unsigned(expression)
- Converts
expressioninto an unsigned expression of the same bit-width. - MSB is treated as a normal bit, not a sign bit.
Example:
reg signed [3:0] b = 4'b1000; // -8 (signed) $display("%0d", $unsigned(b)); // 8
Concept understood? Let's apply and learn for real