问题
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