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];
3

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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.
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.
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.
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: people.eecs.berkeley.edu/~rcs/research/interactive_latency.html
It seems array of 1 bit size element cannot be created in c / c++ for now. I will accept your answer. Thanks
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.