2

In c / c++, we can define a variable with 1 bit in memory: like unsigned char value : 1;

Is there a way to declare an array of 1 bit elements? like in sudo code below:

unsigned char : 1 data[10];
Blaze
  • 16,736
  • 2
  • 25
  • 44
Xiong Zou
  • 77
  • 5

1 Answers1

7

The problem is that in most implementations, the 1 bit variable will still occupy 1 byte of memory because that's the way the memory is addressed. If you have a big array of such values, however, then you can work around that. One such solution is std::bitset. You can make one like this:

#include <bitset>
std::bitset<64> data;

You can manipulate bits using the set, reset and flip operations (setting it to 1, 0 or toggling it). You can access a bit using [], for instance

if (data[5]) { ...

Check out a nice example here.

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • Thanks for your solution, however we cannot control the exact memory layout of std::bitset, as what we can with array. for example sizeof(std::bitset<8>) or std::sizeof(std::bitset<64>) always return 8 bytes. it limits its usage especially when we would like to use union to get bits of an integer. – Xiong Zou Nov 27 '18 at 08:51
  • And it is not efficient as array. std::bitset<> would use bit operations << or >> and & to get bit value at an index. If we have no other choices, we might write our own bitset to control the memory layout. I am wondering whether we can define array with elements with size of 1 bit each that we donot need extra bit operations. – Xiong Zou Nov 27 '18 at 09:06
  • You could pack 8 bit fields (`unsigned int a: 1;`) into one `struct` and if you're lucky, the compiler will optimize it properly. You can then use those structs to make your own bitset. I wouldn't recommend it, however. – Blaze Nov 27 '18 at 09:15
  • Yes, you are right, @Blaze. however if we do that, then we cannot access them by operator[] directly. We now need to do if else check to choose the correct bits. Branching is more costly than bit operations. branch mis-predict is about 3ns each referring to this url: https://people.eecs.berkeley.edu/~rcs/research/interactive_latency.html – Xiong Zou Nov 27 '18 at 09:25
  • It seems array of 1 bit size element cannot be created in c / c++ for now. I will accept your answer. Thanks – Xiong Zou Nov 29 '18 at 03:12
  • How do you do this in C? – ak_app May 04 '19 at 13:44
  • @ak_app see this answer for a rough idea: https://stackoverflow.com/a/4372519/10411602 – Blaze May 06 '19 at 06:01