Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of a Packed Structure of Bools

Tags:

c++

memory

If 1 bool is 1byte [8 bits] then would a packed structure of 4 bools be 32bits or 4? The pack directive removes the alignment requirement, but would it make sets of bools more efficient [memory wise]?

like image 363
monksy Avatar asked Oct 27 '10 17:10

monksy


People also ask

How big is a bool C#?

The actual size of a C# bool is one byte.

How much space do you think a Boolean data type takes up?

bool The bool type takes one byte and stores a value of true (1) or false(0). The size of a bool is 1 true 1 1 1 false 0 0 0 Press any key to continue . . . int is the integer data type.

What is the size of a Boolean variable in C ++? 1 bit 1 byte 4 bytes 2 bytes?

1 Answer. The explanation: Boolean uses only 1 bit as it stores only truth values which can be true(1) or false(0).


3 Answers

Yes. Even a packed structure of booleans will use at least 8 bits per boolean. Unless you use bit fields.

like image 72
John Calsbeek Avatar answered Oct 13 '22 05:10

John Calsbeek


4 bools.

Each bool needs a unique address (as you can take a bool's address). If you use a bitfield, you can reduce the size to 1 bool, but you won't be able to get the address of an individual bitfield.

like image 27
MSN Avatar answered Oct 13 '22 05:10

MSN


The size of a bool could possibly vary from OS to OS and language to language. I've seen it being a byte, a word and an int (which in turn could be anything as well). But if sizeof(bool) is 1, then a packed structure of bools will be 4 (bytes) (thus 32 bits)

Rather than messing with packing and alignment, why not use:

std::vector<bool>

From : http://www.cplusplus.com/reference/stl/vector/

It is optimized (or should be) internally to be a bitfield. Try it, you'll see the memory it uses is consistent with a single bit per value.

Otherwise you can always roll your own library or use the limited FD_SET macros.

like image 35
Marius Avatar answered Oct 13 '22 04:10

Marius