Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++中10位或12位字段数据类型 是否可以定义一些奇数大小的数据类型而不是使用C++中的类型DEF 10位或12位的标准类型?< P>可以使用位字段来表示: struct bit_field { unsigned x: 10; // 10 bits };_C++_Variables_Abstract Data Type - Fatal编程技术网

C++中10位或12位字段数据类型 是否可以定义一些奇数大小的数据类型而不是使用C++中的类型DEF 10位或12位的标准类型?< P>可以使用位字段来表示: struct bit_field { unsigned x: 10; // 10 bits };

C++中10位或12位字段数据类型 是否可以定义一些奇数大小的数据类型而不是使用C++中的类型DEF 10位或12位的标准类型?< P>可以使用位字段来表示: struct bit_field { unsigned x: 10; // 10 bits };,c++,variables,abstract-data-type,C++,Variables,Abstract Data Type,像这样使用它 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

像这样使用它

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;
}

本身无效。

您可以使用位字段:

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;
}

本身无效。

为此使用位字段。我想这应该有助于使用位字段。如果您使用位字段,我想这应该会有所帮助。但是,请记住,位字段仍然打包在某些固有类型中。在下面粘贴的示例中,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 = %u\n", d.has_foo);
  printf("d.foo_count = %d\n", d.foo_count);
  printf("sizeof(d) = %lu\n", sizeof(d));

  return 0;
}

如果您使用位字段,则可以进行排序。但是,请记住,位字段仍然打包在某些固有类型中。在下面粘贴的示例中,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 = %u\n", d.has_foo);
  printf("d.foo_count = %d\n", d.foo_count);
  printf("sizeof(d) = %lu\n", sizeof(d));

  return 0;
}

有一些类似的替代方案,但真正的问题是用例是什么。也就是说,这看起来像是X-Y问题,你有一个问题X,你认为Y是解决方案,你问的是Y,而没有提供真正的问题X。为什么你想要奇数位数的类型?空间限制?是否保证该值在某个范围内?好奇?有一些类似的替代方案,但真正的问题是用例是什么。也就是说,这看起来像是X-Y问题,你有一个问题X,你认为Y是解决方案,你问的是Y,而没有提供真正的问题X。为什么你想要奇数位数的类型?空间限制?是否保证该值在某个范围内?好奇?sizeof返回大小\u t哪个sizeof返回大小\u t哪个