module test();
int a = 256;
int b;
initial
begin
b = real'(a)/6;
$display("b = %0d", b);
b = a/6;
$display("b = %0d", b);
end
endmodule
// Output
b = 43
b = 42
Now as per 1800-2012 LRM, Topic 6.12.2,
Real numbers shall be converted to integers by rounding the real number to the nearest integer, rather than
by truncating it. Implicit conversion shall take place when a real number is assigned to an integer. If the
fractional part of the real number is exactly 0.5, it shall be rounded away from zero.
Then why in the 2nd case, b is not getting value of the nearest integer (which is 43, because 256/6 = 42.67)?
Yes. C behaves the same way, although the C standard defines it a bit more explicitly than the SystemVerilog standard.
From C11:
When integers are divided, the result of the / operator is the algebraic quotient with any
fractional part discarded. …This is often called “truncation toward zero”.
Ok So Should the following both code give same results?
module test();
int b, tp;
int d = 41;
initial
begin
tp = ((d + 2) / 3);
$display("tp = %0d", tp);
tp = ((d + 2) / 3) - 0.5;
$display("tp = %0d", tp);
end
endmodule
1st one should truncate the results, because both numerator & denominator are integer. 2nd one will take the nearest integer, because subtracting 0.5 will make the result a real value.