Why does my S-function return inaccurate results when generated from C-code containing a right-shift operator?

4 views (last 30 days)
I am using S-function builder to create an S-function from C Code. The C code contains the following statements:
unsigned int uproduct;
uproduct = 0xffffffff>>32;
I expect uproduct to be "0" but it is "4294967295" instead.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
The issue occurs because in the following expression the hex constant fits into a 32-bit unsigned integer.
uproduct = 0xffffffff>>32;
The right shift operation is undefined when shifting a 32 bit number by 32 bits. The result in such a case is not standardized and different compilers handle this differently. The LCC compiler results in uproduct being 4294967295 whereas Microsoft Visual Studio C++ Enterprise Edition 2005 will result in uproduct being 0.
This issue is a limitation of the C language definition and is not due to bug in the compiler or Simulink. This is mentioned in Section 6.5.7 Bitwise shift operators, page 86 of the Draft C standard, as given below.
"The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined."
This document can be found at the following link:
<http://std.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.pdf>
This is also stated in the Microsoft developer network as given below.
"The results are undefined if the right operand of a shift expression is negative or if the right operand is greater than or equal to the number of bits in the promoted left operand."
For more information, refer to the following link:
<http://msdn.microsoft.com/en-us/library/336xbhcz.aspx>

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!