c 按位取反转换问题
下面的代码:
signed char sc = ~0xFC;
unsigned char uc = ~0xFC;
编译时给我以下警告:
integer conversion resulted in truncation
integer conversion resulted in truncation
- 为什么我会收到这些警告
- 我如何编写我的代码,这样我就不会收到这些警告(不使用#pragmas)
比x,
我正在使用IAR编译器8051,
做使用其他编译器进行编译时是否会收到类似的警告?
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
- why do i get these warnings
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为十六进制文字在像
0xFC
那样编写时被视为int。为了避免警告,只需将它们转换为将数字截断为仅1个字节:0xFC
被视为在 32 位架构上为 0x000000FC
,因此当您应用 not 时,您将获得0xFFFFFF03
,这意味着当您将此结果分配给 char 时,3 个最相关的字节将被丢弃,并且编译器会发出警告你关于它。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:0xFC
is considered0x000000FC
on a 32 bit architecture, so when you apply not you obtain0xFFFFFF03
, 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.在 C 中,算术至少以
int
的大小执行。这意味着,~0xFC
将返回一个int
。更重要的是,这个值是0xFF03
,它远远超出了char
(有符号或无符号)的范围。因此,作业会给出两个警告。您可以尝试
查看编译器是否知道结果在
char
范围内(添加& 0xFF
后 gcc 不会抱怨)。您还可以尝试添加显式强制转换:或者,由于可以轻松计算该值,为什么不只是
In C, arithmetics are performed at least at the size of
int
. That means,~0xFC
will return anint
. Even more, this value is0xFF03
which is way beyond the range ofchar
(signed or not).Therefore, the assignment will give the two warnings. You could try
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:or, as the value can be easily computed, why not just