Yusuf Selim KARATAS
Yusuf Selim KARATAS

Reputation: 115

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.

Upvotes: 1

Views: 2044

Answers (2)

Lundin
Lundin

Reputation: 215115

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.

Upvotes: 0

Potatoswatter
Potatoswatter

Reputation: 137930

When they say "character data," they mean text. Text characters cannot be negative, so they are giving tips on ensuring that codes in e.g. 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.

Upvotes: 1

Related Questions