Thats not a stupid question. It is right that bool values usually should take up only 1 bit of space, but the smallest unit a cpu can load from RAM is a Byte (8bit). So you have to send at least 1 Byte to the cpu even if it holds less information.
If you dont want to waste the other 7 bits you can use bitwise operations to handle up to 8 boolean values within 1 Byte:
For example you want to describe what components a entity (like a player entity or enemy entity etc.) have with booleans. You can use a bitmask for that.
index:
0 - represents position
1 - sprite
2 - state
3 - movable
4-7 - unused
7 6 5 4 3 2 1 0 - index of the Byte
0 0 0 0 1 0 1 1 - actual bitmask of an entity
So as u can see this entity has position, sprite and is movable. But how to access this information?
There come bitwise operatins in handy.
If u want to know if this entity has a position for example, you need another byte with only that flag u want to investigate as true.
That would be 0 0 0 0 0 0 0 1 and you can put them together with the bitwise operator & unlike &&.
Like you may assume bitwise means those 'And' checks ll be done for every bit and puts the result in the related index.
So for our example it would be:
0 0 0 0 1 0 1 1 - the entity
& & & & & & & &
0 0 0 0 0 0 0 1 - the position mask
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
0 0 0 0 0 0 0 1 - the result, which is true
So the result is true and we can say our entity has a position component and we can handle it likewise.
So how to create those bitmasks?
Every digit of the byte represents a power of 2 (2 ^ index). So u can use for example a char and set it to 1 (== 2^0) to turn on the most right digit for example. If u want to turn on the most left you need to set it to 128).
here is a short example:
Code: Select all
unsigned char byteA = 1; //0000 0001
unsigned char byteB = 128; // 1000 0000
unsigned char bitmask = 1 + 8 + 64; // 0100 1001
std::cout << (bool)(byteA & byteB) << std::endl; //returns false
std::cout << (bool)(byteA & bitmask) << std::endl; //returns true
std::cout << (bool)(byteB & bitmask) << std::endl; //returns false
Hope this is understandable, iam not a teacher or something like that.
Here is an overview about the stuff you can do with that:
https://en.wikipedia.org/wiki/Bitwise_operations_in_C