cancel
Showing results for 
Search instead for 
Did you mean: 

char to short - unexpected casting behavior

Posted on August 21, 2012 at 19:45

Hi all,

I use STM32F205xx for my project but I did the same results with STM32VL Discovery kit.

I debug in Atollic TrueSTUDIO 2.3.0 Lite and I tried TrueSTUDIO 3.1. too.

The problem is that code 

  char a = -50;

  short b = a;

does cast negative values correctly. Internal representation of char should be signed and therefore b variable should be -50 and not 206, which is the result.

I checked this in VisualStudio and the result was -50 as expected. Another brand controller does it as expected.

I checked also disassembly listing. The code for other controller uses signed extend of data for this cast. Atollic makes a simple copy without signed extension.

Do I understand something wrong or is it a problem of a compiler?

How to deal with it correctly? Is it about settings of the compiler?

Thank you for your reactions in advance
2 REPLIES 2
Posted on August 21, 2012 at 20:38

Probably because GCC thinks 'char' is 'unsigned char' by default.

The standard does not specify if plain

char

is signed or unsigned. Check the values of CHAR_MIN and CHAR_MAX as defined in limits.h, and if __CHAR_UNSIGNED__ is defined or not.

http://www.linuxtopia.org/online_books/an_introduction_to_gcc/gccintro_html

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Posted on August 22, 2012 at 12:29

Thank you for the quick reply.

Yes, I expected char to be specified as signed, but it is not.

So I will continue using ''signed char'' type declaration instead of ''char''

Btw. when calling a functions like this, the compiller warns me about difference in signednes.

void function (char * c);

 

 

unsigned char aaa;

 

function (&aaa);