与(签字)枚举值按位运算 [英] Bitwise operation with (signed) enum value

查看:150
本文介绍了与(签字)枚举值按位运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的枚举值标记:

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使用的签署的INT(或短,或字符)作为底层类型枚举的,我能找到的唯一选择涉及大小,而不是带符号(--enum - 是 - INT)。

According to MISRA-C:2004 bitwise operations shall not be done with a signed type. Unfortunately, My compiler IAR use signed int (or short or char) as underlying type of enums, and the only option I can find relates to the size, not the signedness ("--enum-is-int").

推荐答案

据该的 IAR C / C ++开发指南ARM ,169和211页,你可以,如果你能够定义你的枚举 S的种类在IAR语言扩展( -e 命令行选项,或项目的>的选项的>的 C / C ++编译器的>的语言的>的允许IAR扩展的在IDE)。

According to the IAR C/C++ Development Guide for ARM, pages 169 and 211, you can define the type of your enums if you enable the IAR language extensions (-e command-line option, or Project > Options > C/C++ Compiler > Language > Allow IAR extensions in the IDE).

在特别的,你应该定义一个额外的哨兵的价值,以确保编译器选择正确的类型。它$符号类型p $ pfers,并采用最小的可能整数类型,所以哨兵应该是最大的正整数对应的无符号整型可以形容。例如,

In particular, you should define an extra "sentinel" value, to make sure the compiler chooses the correct type. It prefers signed types, and uses smallest possible integer type, so the sentinel should be the largest positive integer the corresponding unsigned integer type can describe. For example,

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

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

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

这篇关于与(签字)枚举值按位运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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