gpt4 book ai didi

c - 带(有符号)枚举值的按位运算

转载 作者:行者123 更新时间:2023-12-04 02:19:29 26 4
gpt4 key购买 nike

我正在为标志使用枚举器值:

typedef enum
{
a = 0x00,
b = 0x01u, // the u has no influence, as expected
c = 0x02u, // the u has no influence, as expected
...
} enum_name;

volatile unsigned char* reg = SomeAddress;
*reg |= b;

根据 MISRA-C:2004,按位运算不得使用有符号类型来完成。不幸的是,我的编译器 IAR 使用 signed int(或 short 或 char)作为枚举的基础类型,我能找到的唯一选项与大小有关,而不是符号(“--enum-is- int”)。

最佳答案

根据IAR C/C++ Development Guide for ARM ,第 169 和 211 页,如果启用 IAR 语言扩展(-e 命令行选项,或 Project<,则可以定义 enum 的类型/em>> 选项> C/C++ 编译器> 语言> 在 IDE 中允许 IAR 扩展

特别是,您应该定义一个额外的“sentinel”值,以确保编译器选择正确的类型。它更喜欢有符号类型,并使用尽可能小的整数类型,因此标记应该是相应无符号整数类型可以描述的最大正整数。例如,

typedef enum {
/* ... */
enum_u8_sentinel = 255U
} enum_u8;

typedef enum {
/* ... */
enum_u16_sentinel = 65535U
} enum_u16;

typedef enum {
/* ... */
enum_u32_sentinel = 4294967295UL
} enum_u32;

关于c - 带(有符号)枚举值的按位运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31780026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com