1

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++ ?

Hassan Rizwan
  • 11
  • 1
  • 1
  • 4
  • 1
    There are some alternatives that can resemble this, but the real question is what the use case is. That is, this seems like the X-Y problem, you have a problem X, for which you believe Y is the solution and you are asking about Y without providing the real problem X. Why do you want types with odd number of bits? Space constrains? Guarantee that the value is within a range? Curiosity? – David Rodríguez - dribeas Apr 09 '15 at 08:45
  • 4
    [Create a 10-bit data type in C/C++](http://stackoverflow.com/q/37473539/995714) – phuclv May 28 '16 at 03:44

3 Answers3

5

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.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
1

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;
}
Tom Dial
  • 59
  • 4
  • 2
    `sizeof` returns `size_t` which [must be printed using `%zu`](https://stackoverflow.com/q/940087/995714) – phuclv Aug 07 '18 at 08:04
0

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

Guru
  • 11
  • 2