10 or 12 bit field data type in C ++

Is it possible to define an odd-sized data type instead of standard types using type-def, such as 10 bits or 12 bits in C ++?

+1
source share
3 answers

You can use a bit for this:

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

and use it like

 bit_field b; bx = 15; 

Example:

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

AFAIK, there is no way to have a bit field outside a struct , i.e.

 unsigned x: 10; 

not valid by itself.

+3
source

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

 #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; } 
+1
source
0
source

All Articles