相关疑难解决方法(0)

C中的位域操作

在C中用单位测试和设置单个位的经典问题可能是最常见的中级编程技能之一.您可以使用简单的位掩码进行设置和测试

unsigned int mask = 1<<11;

if (value & mask) {....} // Test for the bit
value |= mask;    // set the bit
value &= ~mask;   // clear the bit
Run Code Online (Sandbox Code Playgroud)

一篇有趣的博客文章认为,这容易出错,难以维护,而且做法不佳.C语言本身提供了类型安全和可移植的位级访问:

typedef unsigned int boolean_t;
#define FALSE 0
#define TRUE !FALSE
typedef union {
        struct {
                boolean_t user:1;
                boolean_t zero:1;
                boolean_t force:1;
                int :28;                /* unused */
                boolean_t compat:1;     /* bit 31 */
        };
        int raw;
} flags_t;

int
create_object(flags_t flags)
{
        boolean_t is_compat = flags.compat;

        if (is_compat) …
Run Code Online (Sandbox Code Playgroud)

c bit-manipulation

46
推荐指数
11
解决办法
5万
查看次数

除int之外的其他类型的位域?

我有一个代码,它使用如下声明的位字段

typedef struct my{
    const char *name;
    uint8_t is_alpha : 1;   
    uint8_t is_hwaccel : 1; 
    uint8_t x_chroma_shift; 
    uint8_t y_chroma_shift; 

} mystr; 
Run Code Online (Sandbox Code Playgroud)

uint8_t是typedef'ed unsigned char.

使用此位字段在MS-VS 2008中构建代码会发出如下警告:

imgconvert.c(60) : warning C4214: nonstandard extension used : bit-field types other than int.
  1. 使用除int之外的其他类型的位字段是否存在任何问题/潜在问题?为什么警告?
  2. C99 C语言规范是否允许使用int类型的bit-fileds以外的其他文件?

c visual-c++ bit-fields

10
推荐指数
1
解决办法
8132
查看次数

标签 统计

c ×2

bit-fields ×1

bit-manipulation ×1

visual-c++ ×1