简体   繁体   中英

Int8_t to Int16_t Conversion in C

I have a C codes in my project. In some part of the codes I have used conversion from int8_t to int32_t conversion directly and made a Polyspace analysis.

In polyspace analysis, it says that this is prone to error and I need to convert first to char than to int32_t. I did not understand well why this is needed.

Also I have seen similar expression in link below which says:

Signed character data must be converted to unsigned char before being assigned or converted to a larger signed type. This rule applies to both signed char and (plain) char characters on implementations where char is defined to have the same range, representation, and behaviors as signed char. Source website

I have tried same conversion on my PC with Dev-C

My code is:

#include <stdio.h>
#include <stdint.h>
void main(void)
{
    int8_t b = -3;
    int32_t b_32 = (int32_t) b;
    printf("%d \n",b);
    printf("%d \n",b_32);
}

And output seems no problem exists:

-3

-3

Process exited after 0.0807 seconds with return value 4 Press any key to continue. . .

So, I see here no problem. Why conversion to char is needed?

Thanks.

When they say "character data," they mean text. Text characters cannot be negative, so they are giving tips on ensuring that codes in eg ISO 8859 format will stay in the 0-255 range.

Since you are treating actual signed numbers, disregard the advice and cast directly from int8_t to int32_t .

If you read the referred CERT-C rule you link to, the actual concern is to use char type in arithmetic or when storing raw values. They are also concerned about implicit type promotion. See these posts for more info about these issues:

Is char signed or unsigned by default?
Implicit type promotion rules

None of the concerns related to signedness of char or implicit integer promotion are present in your expression int32_t b_32 = (int32_t) b; . Notably, b is not of type char . No conversion to unsigned is necessary - the code is fine. The cast isn't needed either. Your tool is giving a false positive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM