I write a program with highly memory cost requirement and I want save memory with no performance lost. So I want change every variable which has only two situations into bit.
But I can't find bit type in C++ and bitset
in STL is always multiples of 4 byte in 32-bit machine.
Writing a data struct to manage bits will cause performance lost.
Is there any way to declare a bit value just like bit a;
?
Thanks everyone. At last the answer I want is:"you can't buy half bytes in C++".
Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared.
Setting a bit means that if K-th bit is 0, then set it to 1 and if it is 1 then leave it unchanged. Clearing a bit means that if K-th bit is 1, then clear it to 0 and if it is 0 then leave it unchanged. Toggling a bit means that if K-th bit is 1, then change it to 0 and if it is 0 then change it to 1.
A byte is typically 8 bits. C character data type requires one byte of storage. A file is a sequence of bytes. A size of the file is the number of bytes within the file. Although all files are a sequence of bytes,m files can be regarded as text files or binary files.
There is none. The smallest addressable entity is a byte. This is the char or unsigned char type. (The best type is the integer because it is aligned to the width of your processor and thus fastest to fetch and work on)
To work with bits you need to use boolean operators and mask/shift your data in the larger types. Or work with STL bitsets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With