结构C中“:”的含义是什么

时间:2012-06-25 21:55:50

标签: c struct

  

可能重复:
  What does 'unsigned temp:3' means

  struct Test
  {
      unsigned a : 5;
      unsigned b : 2;
      unsigned c : 1;
      unsigned d : 5;
  };

  Test B;
  printf("%u %u %u %u", B.a, B.b, B.c, B.d); // output: 0 0 0 0
  static struct   Test A = { 1, 2, 3, 4};

有人可以解释我:在结构中的目的是什么,printf只输出0所以我认为这些不是默认值,但它们是什么呢?

也有人可以解释为什么A.a, A.b, A.c, A.d输出1, 2, 1, 4代替1, 2, 3, 4

3 个答案:

答案 0 :(得分:9)

这是bit field

它基本上告诉编译器hey, this variable only needs to be x bits wide, so pack the rest of the fields in accordingly, OK

答案 1 :(得分:2)

这些是位字段,请参阅this Wikipeadia section on Bitfields或此参考资料bit fields

:后面的数字表示要为左侧标识符保留多少位。这允许您通过紧密打包数据来分配比通常情况下更少的空间。您只能在structunion s。

中执行此操作

这是位字段的短tutorial

答案 2 :(得分:0)

简单说明:您可以指定变量的位数。 (您不能指定比该类型的原始大小更多的位。)
编辑:您的第三个变量只打印1,因为它只有1 bit来存储其数据。因此,该值只能是01。十进制值3由二进制格式的11表示。因此,无论哪个位被截断,您最终都会在变量中存储1