bandana
bandana

Reputation: 3612

c bitwise negation conversion question

the following code:

signed char sc = ~0xFC;
unsigned char uc = ~0xFC;

when compiled gives me the following warnings:

integer conversion resulted in truncation
integer conversion resulted in truncation
  1. why do i get these warnings
  2. how do i write my code, so that i dont get these warnings (without using #pragmas)

thanx,

i'm using IAR Compiler for 8051,

do you get similar warnings when compiling using other compilers?

Upvotes: 3

Views: 1666

Answers (2)

kennytm
kennytm

Reputation: 523334

In C, arithmetics are performed at least at the size of int. That means, ~0xFC will return an int. Even more, this value is 0xFF03 which is way beyond the range of char (signed or not).

Therefore, the assignment will give the two warnings. You could try

signed char sc = ~0xFC & 0xFF;

to see if the compiler knows that the result is within the range of char (gcc won't complain after adding the & 0xFF). You could also try to add an explicit cast:

signed char sc = (signed char)~0xFC;
// also possible:
// signed char sc = ~(signed char)0xFC;

or, as the value can be easily computed, why not just

signed char sc = 3;

Upvotes: 2

Jack
Jack

Reputation: 133587

Because hexadecimal literals are considered int when written like you did 0xFC.. to avoid the warning just cast them to truncate the number to just 1 byte:

~((char) 0xFC)

0xFC is considered 0x000000FC on a 32 bit architecture, so when you apply not you obtain 0xFFFFFF03, this means that when you assign this result to a char the 3 most relevant bytes are just discarded and the compiler warns you about it.

Upvotes: 6

Related Questions