Effacer les filtres
Effacer les filtres

Convertion from U16 in U8 results overflow. Why?

31 vues (au cours des 30 derniers jours)
Cristina Golie
Cristina Golie le 10 Avr 2015
Hello all,
I made the following example:
typedef unsigned int U16;
typedef unsigned char U8;
// case 1;
U16 a = 0x0FFF;
U16 b = 0x0E00;
U8 c = 0x00;
//case 2:
U16 d = 0xFFFF;
U16 e = 0x0011;
U16 f = 0;
void main()
{ //case 1:
c = (U8) (a-b); // -> red check overflow
//case 2:
f = (U8) ((d + e)&0x00FF); // + red warning -> no effect of 0x00FF
}
When I run the Polyspace (Code Prover R2014b) analysis, I receive the following red checks:
1) Error: operation [conversion from unsigned int16 to unsigned int8] on scalar overflows (result is always strictly greater than MAX UINT8) conversion from unsigned int 16 to unsigned int 8
2) Error: operation [+] on scalar overflows (result is always strictly greater than MAX UINT16) operator + on type unsigned int 16
If I change the code from:
c = (U8) (a-b);
to
c = (U8) ((a-b)&0x00FF);
I don't receive the first red warning. Which is the correct configuration for overflow for no error occurring?
  1 commentaire
Titus Edelhofer
Titus Edelhofer le 22 Avr 2015
Hi Christina,
is your question answered with the answers of Alex and myself?
Titus

Connectez-vous pour commenter.

Réponse acceptée

Alexandre De Barros
Alexandre De Barros le 13 Avr 2015
Modifié(e) : MathWorks Support Team le 10 Jan 2023
Hi,
I will also add that Polyspace is raising an overflow here because in your Polyspace project, you have specified an option to detect overflows on unsigned (see Check Behavior). For more information, see: https://www.mathworks.com/help/codeprover/ref/overflowmodeforunsignedintegerunsignedintegeroverflows.html.
The C standard says that there is no overflow on unsigned types (a wrap-around is taking place if that happens), but Polyspace can be stricter than the ANSI C standard.
So if you want to get rid of this overflow on unsigned, you have to use the default mode for detecting overflow (signed only).
Best regards,
Alexandre
  1 commentaire
Cristina Golie
Cristina Golie le 26 Août 2015
Hi,
Thank you for information.

Connectez-vous pour commenter.

Plus de réponses (1)

Titus Edelhofer
Titus Edelhofer le 10 Avr 2015
Modifié(e) : Titus Edelhofer le 10 Avr 2015
Hi,
hmm, I guess the first error is explainable: you indeed have an overflow here.
hex2dec('0FFF')-hex2dec('0E00')
ans =
511
which is larger than 255. This overflows when cast to U8.
The second error is also correct: your plus operation overflows in U16. Doing the "&" afterwards does not help here, because the error occurred inside the (d+e).
last but not least:
c = (U8) ((a-b)&0x00FF);
does not error, because (a-b) is fine (it's done in U16 and a>b). The "&" "removes" the bits larger than 255. Then casting to U8 is safe.
Titus

Community Treasure Hunt

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

Start Hunting!

Translated by