Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a bit in C++

Tags:

c++

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++".

like image 296
zzy Avatar asked May 08 '14 06:05

zzy


People also ask

What is a bit field 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.

How do you set a bit?

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.

What is bit and byte in C?

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.


1 Answers

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.

like image 198
meandbug Avatar answered Oct 01 '22 12:10

meandbug