10 or 12 bit field data type in C++ [duplicate]

假如想象 提交于 2019-12-18 07:24:48

问题


Is it possible to define some odd sized data type instead of the standard types using type-def like 10 bit or 12 bit in C++ ?


回答1:


You can use a bitfield for that:

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

and use it like

bit_field b;
b.x = 15;

Example:

#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, there is no way of having a bitfield outside a struct, i.e.

unsigned x: 10; 

by itself is invalid.




回答2:


Sort of, if you use bit fields. However, bear in mind that bit fields are still packed within some intrinsic type. In the example pasted below, both has_foo and foo_count are "packed" inside of an unsigned integer, which on my machine, uses four bytes.

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



回答3:


Use Bitfields for this. Guess this should help http://www.cs.cf.ac.uk/Dave/C/node13.html#SECTION001320000000000000000



来源:https://stackoverflow.com/questions/29529979/10-or-12-bit-field-data-type-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!