【问题标题】:What is meaning of ":" in struct C [duplicate]struct C中的“:”是什么意思[重复]
【发布时间】:2012-06-25 21:55:50
【问题描述】:

可能重复:
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

【问题讨论】:

    标签: c struct


    【解决方案1】:

    那是bit field

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

    【讨论】:

      【解决方案2】:

      这些是位字段,请参阅this Wikipeadia section on Bitfields 或有关bit fields 的参考

      : 后面的数字表示要为左侧的标识符保留多少位。与通常紧密打包数据的情况相比,这允许您分配更少的空间。您只能在 structs 或 unions 中执行此操作。

      这是一个简短的tutorial 位域。

      【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-17
        • 1970-01-01
        • 2011-01-22
        • 2014-03-23
        • 2017-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多