C++ 中的 10 位或 12 位字段数据类型



是否可以使用type-def(如10位或12位)定义一些奇数大小的数据类型而不是标准类型C++?

您可以使用位字段:

struct bit_field
{
    unsigned x: 10; // 10 bits
};

并像使用它一样使用

bit_field b;
b.x = 15;

例:

#include <iostream>
struct bit_field
{
    unsigned x: 10; // 10 bits
};
int main()
{
    bit_field b;
    b.x = 1023;
    std::cout << b.x << std::endl;
    b.x = 1024; // now we overflow our 10 bits
    std::cout << b.x << std::endl;
}

AFAIK,在struct之外没有位域,即

unsigned x: 10; 

本身是无效的。

有点,如果你使用位字段。但是,请记住,位字段仍打包在某些内部类型中。在下面粘贴的示例中,has_foo 和 foo_count 都"打包"在一个无符号整数中,在我的机器上,该整数使用四个字节。

#include <stdio.h>
struct data {
  unsigned int has_foo : 1;
  unsigned int foo_count : 7;
};
int main(int argc, char* argv[])
{
  data d;
  d.has_foo = 1;
  d.foo_count = 42;
  printf("d.has_foo = %un", d.has_foo);
  printf("d.foo_count = %dn", d.foo_count);
  printf("sizeof(d) = %lun", sizeof(d));
  return 0;
}
为此

使用位域。猜猜这应该对 http://www.cs.cf.ac.uk/Dave/C/node13.html#SECTION001320000000000000000 有所帮助

最新更新