c 按位取反转换问题

发布于 2024-09-17 05:42:35 字数 366 浏览 7 评论 0原文

下面的代码:

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

编译时给我以下警告:

integer conversion resulted in truncation
integer conversion resulted in truncation
  1. 为什么我会收到这些警告
  2. 我如何编写我的代码,这样我就不会收到这些警告(不使用#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
  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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

知足的幸福 2024-09-24 05:42:35

因为十六进制文字在像0xFC那样编写时被视为int。为了避免警告,只需将它们转换为将数字截断为仅1个字节:

~((char) 0xFC)

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:

~((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.

最偏执的依靠 2024-09-24 05:42:35

在 C 中,算术至少以 int 的大小执行。这意味着,~0xFC 将返回一个 int。更重要的是,这个值是0xFF03,它远远超出了char(有符号或无符号)的范围。

因此,作业会给出两个警告。您可以尝试

signed char sc = ~0xFC & 0xFF;

查看编译器是否知道结果在 char 范围内(添加 & 0xFF 后 gcc 不会抱怨)。您还可以尝试添加显式强制转换:

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

或者,由于可以轻松计算该值,为什么不只是

signed char sc = 3;

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文