【问题标题】:Structure member declaration with " : 1 "带有“ : 1 ”的结构成员声明
【发布时间】:2013-09-07 23:11:32
【问题描述】:

我在 linux 内核文件 include/sound/soc-dapm.h 中找到了这个结构。 我对其成员的声明感到困惑。我在谷歌上寻找它,但找不到任何有用的东西。 如果有人可以解释为什么每个变量声明后都有 :1 ,那将是很大的帮助。这是部分代码。

struct snd_soc_dapm_widget {

    unsigned int off_val;                   /* off state value */
    unsigned char power:1;                  /* block power status */
    unsigned char invert:1;                 /* invert the power bit */
    unsigned char active:1;                 /* active stream on DAC, ADC's */
    unsigned char connected:1;              /* connected codec pin */

}

谢谢。

【问题讨论】:

标签: c variables structure declaration


【解决方案1】:

它被称为"bit field"。它用于内存优化。它使您可以在比其他方式需要的更少的空间中存储类型。

(来自上述链接的代码)。

#include <stdio.h>
#include <string.h>

struct
{
  unsigned int age : 3;
} Age;

int main( )
{
   Age.age = 4;
   printf( "Sizeof( Age ) : %d\n", sizeof(Age) );
   printf( "Age.age : %d\n", Age.age );

   Age.age = 7;
   printf( "Age.age : %d\n", Age.age );

   Age.age = 8;
   printf( "Age.age : %d\n", Age.age );

   return 0;
}

输出:

Sizeof( Age ) : 4
Age.age : 4
Age.age : 7
Age.age : 0 

注意分配给大于 23 的值如何将 Age.age 的大小减小到 0?这是因为:3。这也意味着您的 unsigned char active:1; 示例非常适合存储布尔值:它可以为真或假,它不会意外存储 255(这恰好是 unsigned char 的最大值)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2020-09-02
    • 1970-01-01
    • 2013-05-19
    • 2013-01-02
    • 1970-01-01
    • 2013-05-06
    相关资源
    最近更新 更多