简体   繁体   English

c按位否定转换问题

[英]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) 我如何编写我的代码,以便我不会得到这些警告(不使用#pragmas)

thanx, 感谢名单,

i'm using IAR Compiler for 8051, 我正在使用IAR Compiler for 8051,

do you get similar warnings when compiling using other compilers? 在使用其他编译器进行编译时,您会收到类似的警告吗?

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: 因为十六进制文字在写入时被认为是int,就像你做的那样0xFC ..为了避免警告,只是0xFC它们将数字截断为仅1个字节:

~((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. 0xFC被认为是0x000000FC在32位架构,所以当你申请你不获得0xFFFFFF03 ,这意味着,当你这个结果赋值给一个char 3个最相关的字节只是被丢弃,而编译器警告你一下吧。

In C, arithmetics are performed at least at the size of int . 在C中,算术至少以int的大小进行。 That means, ~0xFC will return an int . 这意味着, ~0xFC将返回一个int Even more, this value is 0xFF03 which is way beyond the range of char (signed or not). 更重要的是,这个值是0xFF03 ,这超出了char (有符号或无符号)的范围。

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 ). 查看编译器是否知道结果在char范围内(gcc在添加& 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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