禁食前警告:"Arithmetic Overflow: 32-bit value is shifted, then cast to 64-bit value."

Prefast Warning:"Arithmetic Overflow: 32-bit value is shifted, then cast to 64-bit value."

我已经声明了这样的宏:

#define F_MASK_4_BIT 0xF
#define GET_F_4BIT_MASK(F, P) (((F) & (F_MASK_4_BIT << (P * 4))) >> (4 * P))

像这样使用宏:

uint8_t Feature = GET_F_4BIT_MASK(E, P);

其中 Euint64_t 数据类型 Puint8_t 数据类型

Prefast 发出警告:C6297:算术溢出:移位 32 位值,然后转换为 64 位值。结果可能不是预期值。

如何解决这个问题?

这是不言自明的。如果 P 的任何值大于 7(7*4=28,最大值为 31),则 F_MASK_4_BIT << (P * 4) 将溢出。因为 F_MASK_4_BITint.

类型的整型常量

通过为整数常量使用适当的类型来解决此问题:

#define F_MASK_4_BIT 0xFull