Why are there different casts in the generated code for signed and unsigned values in the Fixed-Point Toolbox 2.1 (R2007b)?

2 views (last 30 days)
I generate code for the attached model. The data conversion code for an unsigned value (line 41) uses an intermediate cast to uint32, where for the signed value this intermediate cast is not inserted (line 47) (code see below)
Can you please explain the difference or explain why the cast is needed or done in the unsigned case and ignored for the signed case. (when changing the hardware configurations to a 16-bit processor, the cast appears in both cases.)
The code is generated using R2007b
35 /* Output and update for atomic system: '<Root>/input scaling' */
36 void casting_question_M_inputscaling(void)
37 {
38 /* DataTypeConversion: '<S2>/Data Type Conversion' incorporates:
39 * Constant: '<Root>/Constant'
40 */
41 casting_question_MPS_B.DataTypeConversion = (uint16_T)((uint32_T)
42 casting_question_MPS_P.Constant_Value * 16777U >> 11);
43
44 /* DataTypeConversion: '<S2>/Data Type Conversion1' incorporates:
45 * Constant: '<Root>/Constant1'
46 */
47 casting_question_MPS_B.DataTypeConversion1 = (int16_T)
48 (casting_question_MPS_P.Constant1_Value * 16777 >> 12);
49 }When

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
The missing cast is due to different scaling factors, see the explaination:
For cast, ideal real world behavior is
V1 = V2;
Replace with scaling equations, assuming zero bias
S1 * Q1 = S2*Q2
Solve for output stored integer
Q1 = (S2/S1) * Q2
For UNSiGNED CAST, substitute actual scaling
Q1 = (0.001/2^-13) * Q2
Q1 = 8.192 * Q2
The generated code is
Q1 = Q2 * 16777U >> 11
Assuming ideal math with no overflows, etc, this is mathematically equivalent to
Q1 = Q2 * 8.19189453125
So * 16777 >> 11 is a fixed point approximation of 8.192
For the SIGNED CAST, the output scaling is different by a factor of two
Q1 = (0.001/2^-12) * Q2
Q1 = 4.096 * Q2
The generated codes * 16777 >> 12 is a fixed point approximation of 4.096.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!