警告:左移计数 >= 类型宽度 [默认启用] [英] warning: left shift count >= width of type [enabled by default]

查看:35
本文介绍了警告:左移计数 >= 类型宽度 [默认启用]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一段代码:

long int compute_data_length(unsigned char* buf, int data_offset) {

long int len;

if(!buf)
    return -1;

switch(data_offset) {
    case 2: {
                len = (buf[2] << 8) | buf[3];
            }
            break;
    case 8: {
                len = (buf[2] << 56) |
                      (buf[3] << 48) |
                      (buf[4] << 40) |
                      (buf[5] << 32) |
                      (buf[6] << 24) |
                      (buf[7] << 16) |
                      (buf[8] <<  8) |
                      (buf[9]      );
            }
            break;
    default: len = -1; break;
}
return len;
}

当我编译时,我收到以下警告:

When I compile, I get the following warning:

math_fun.c:240:21: 警告:左移计数 >= 类型宽度 [默认启用]len = (buf[2] << 56) |^math_fun.c:241:27: 警告:左移计数 >= 类型宽度 [默认启用](buf[3] << 48) |^math_fun.c:242:27: 警告:左移计数 >= 类型宽度 [默认启用](buf[4] << 40) |^math_fun.c:243:27: 警告:左移计数 >= 类型宽度 [默认启用](buf[5] << 32) |

math_fun.c:240:21: warning: left shift count >= width of type [enabled by default] len = (buf[2] << 56) | ^ math_fun.c:241:27: warning: left shift count >= width of type [enabled by default] (buf[3] << 48) | ^ math_fun.c:242:27: warning: left shift count >= width of type [enabled by default] (buf[4] << 40) | ^ math_fun.c:243:27: warning: left shift count >= width of type [enabled by default] (buf[5] << 32) |

如何修复警告?

推荐答案

整数促销转 buf[2] <<56 转化为 (int)buf[2] <<<56 [注 1],但是 int 完全有可能只有 32 位,并且您需要它是无符号的 64 位类型才能使移位有意义.

Integer promotions turn buf[2] << 56 into (int)buf[2] << 56 [Note 1], but it is entirely possible that int only has 32 bits and you need it to be an unsigned 64-bit type for the shift to be meaningful.

您期望 unsigned long 为 64 位,但也可能不是.最好包含 并使用 uint64_t.在任何情况下,您都需要显式转换左移的左操作数:

You're expecting unsigned long to be 64 bits, but it might not be. It would be better to include <stdint.h> and use uint64_t. In any event, you need to explicitly cast the left operands of thE left shift:

((uint64_t)buf[2] << 56) | ...

<小时>

[注 1]:理论上 unsigned charint 一样宽是可能的,在这种情况下,整数提升将是一个 unsigned整数.但这只会发生在不寻常的架构上.


[Note 1]: It's theoretically possible for unsigned char to be as wide as an int, in which case the integer promotion would be to an unsigned int. But that only happens on unusual architectures.

这篇关于警告:左移计数 >= 类型宽度 [默认启用]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆