c - 移位计数大于类型宽度

标签 c types

我有一个接受 int data_length 并执行以下操作的函数:

unsigned char *message = (unsigned char*)malloc(65535 * sizeof(char));
message[2] = (unsigned char)((data_length >> 56) & 255);

我得到以下信息:

warning: right shift count >= width of type [-Wshift-count-overflow]
   message[2] = (unsigned char)((data_length >> 56) & 255);

该程序按预期工作,但我如何才能删除编译器警告(而不禁用它)? 类似的问题似乎没有使用变量作为要插入的数据,因此解决方案似乎是将它们转换为 int 或类似的。

最佳答案

标准不允许移动大于相关类型位宽的量,这样做会调用 undefined behavior .

这在 C standard 的第 6.5.7p3 节中有详细说明。关于位移运算符。

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

如果程序看起来有效,那是运气。您可以对您的程序进行不相关的更改,或者只是在另一台机器上构建它,突然间一切都会停止。

如果 data_length 的大小是 32 位或更少,那么右移 56 就太大了。您只能移动 0 - 31。

关于c - 移位计数大于类型宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52784451/

相关文章:

c - 带线程的递归 Fib、段错误?

haskell - Foundation 中项目类型的目的是什么

c# - 从 C# 中的程序集类型实例化

c - 在字符串中查找未知单词

c - 访问不同 c 文件中 pthread 中的全局变量

c - 为什么 int 类型变量的值即使不在 int 范围内也会被打印?

C 忽略返回值

c++ - uint128_t 没有命名类型

c# - 如何使用 C# 为 Excel 中的单元格设置本地化的短日期格式?

JSON API 规范 - 服务器职责说明