This article is a note about the effect of the bit length of the expression on the result after learning Wei Jiaming Teacher's "Verilog programming Art".
In the program is often necessary to use a simple calculation, simple such as +-, complex has * * (Power operation).
So sometimes the result of the operation is inconsistent with the theory, what is the reason??? It's probably a bit of a long reason.
And look at the following examples:
1, the intermediate results because the bit length is not enough to appear lost:
Reg[3:0] A; Reg[3:0] B; Reg[3:0] C; Reg[3:0] D; Reg[4:0] e; always@(PosedgeCLK)beginC= (A + b) >>1; D= (A + B +0) >>1; E= (A + b) >>1; End Initial begina=0; b=0; CLK=0; F<=0; #(Ten*t) A =6; #(Ten*t) b =6; #(Ten*t) A =2; #(Ten*t) A = -; #(Ten*t) b =Ten; End
The simulation plots:
The results can be seen when A+b < 16, C, D, e results are the same, but when A+b > 15, the results of C, D, e are not the same? What's the reason?
First to analyze the value of C, because both A and B are 4 bits (the maximum value is 15), the operation process is 4 bits, more than 4 bits of the middle value is discarded, so the result is only the low 4 bits of the median value, when a+b = 13+6 = 19 (1 0011), the median value is actually 4 ' b0011, Then move right one to 4 ' b0001 so the result is 1;
For D, because there are 0 (unspecified digits, the default 32-bit) participation, although not change the median size but change the median value of the number of bits, so the median value should be 32bit, the right one after the 32bit, and then take the last 4bit, the result is 4 ' b1001;
Finally, for E, because the number of bits is 5 bits, the ratio is a, B is one more, so the median value according to E to store, the result is also correct.
Summary: In addition calculation, the result is better than addend the most bit more. The median number of digits is determined by the number of digits to the left of the equation and the addend of the maximum number of digits to the right of the equation.
2. The data of the display command is determined by the longest bit in the calculation.
Reg[3:0] A; Reg[3:0] B; Reg[4:0] C; Initial beginCLK=0; A=1; b=4'D4;c =5'D19; #(Ten*t) $display ("answer =%b"A?b:c); End
As can be seen from the above, the value of answer must be B, and B is 4bit, then the result is 4 ' b0100?? Anyway the result is:
The result is 4, but there are 5, what's going on?? Because A?B:C, the most median is C, there is 5bit, so the result is 5bit.
In addition: The result of the expression is not only related to the number of digits, but also to the expression itself.
Effect of expression bit length on the result