CHONG
CHONG

Reputation: 37

How do I make 'bit' array instead of 'int' array?

Conventionally, in C++, upon creating an array, I declare it as an int. However, since I am only dealing with binary numbers (1 and 0 only), I am thinking that is that possible for me to covert the 4 bytes 'int' to 1 bit.

For example

int array1[] = {1,0,0,0,0,1,0}; // -----had total of 32 bytes

Since it's only binary, the memory efficiency is just 1/32 as each int 1's will store as 000000000000000000000000000001 (4 bytes).

So my question is how can I convert all this into bit so that the 32 bytes can be 'compressed' into 1 byte (instead of 8 int of 32 bytes, I want a 8 bits data) ?

Upvotes: 2

Views: 837

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Conventionally, in C++, upon creating an array, I declare it as an int.

There's no such common convention.

However, since I am only dealing with binary numbers (1 and 0 only), I am thinking that is that possible for me to covert the 4 bytes 'int' to 1 bit.

Naturally one might think that this should result in declaring something like

bool array1[]{true,false,false,false,false,true,false};

Though the above implementation just reduces the space used for a single bit to unsigned char, which is the smallest memory unit that can be addressed in c++.


Fortunately c++ provides a specialization of std::vector<bool> that actually space optimizes your bit array as you want to.

Upvotes: 4

user2736738
user2736738

Reputation: 30936

Use std::bitset. I think this is what you want.

I don't know if you are a competitive programmer but sometimes in competitive programming it is required to have 10^9 flags. Then bitset or in sieve's prime determination this is extremely helpful.

#include<bitset>
...
...
bitset<10000000> bs;

..
bs[1]=1;
bs[i]=0;
..etc

Upvotes: 7

Related Questions