Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is it possible to condense `bool` objects within the same byte?

Consider a class with a number of bool attributes

class A
{
  bool a;
  bool b;
  bool c;
  bool d;
  bool e;
  bool f;
};

While each bool object could be represented with a single bit, here each attribute would take a byte (if I am not mistaken). The object would take 6 bytes instead of just 1 byte (6 bits of which would be actually used). The reason being that bits are not addressable, only bytes are.

To condensate the memory a bit, one could use a vector<bool> or a bitset and then access the attributes, by their indices. For example, one could write a get function as

bool A::get_d() {data[3];}

Ideally, I would love being able to directly access the attributes with InstanceOfA.d. Is it possible to do that, while ensuring that all of my 6 bool are being condensed within the same byte?

like image 670
Remi.b Avatar asked Dec 13 '18 00:12

Remi.b


1 Answers

You can use bitfields. Works with Repl.it's gcc version 4.6.3.

#include <iostream>

struct Test 
{
  bool a:1;
  bool b:1;
  bool c:1;
  bool d:1;
  bool e:1;
  bool f:1;
  bool g:1;
  bool h:1;
  //bool i:1; //would increase size to 2 bytes.
};

int main()
{
  Test t;
  std::cout << sizeof(t) << std::endl;
  return 0;
}
like image 135
Phil M Avatar answered Sep 28 '22 07:09

Phil M