Well, first of all in C there’s no such thing bool
, and I don’t even think it’s good practice, but if a variable has 8 bits, then obviously you can store more than two different states in that variable.
What I do below is not something exclusive of any language, can be done in C or C++, here I do in Javascript because it is possible to simulate on the site.
Using a bit of logic and binary operators, you can compare the bit values to check if it is 1
(true
) or 0
(false
).
var bool = 0b00000000 // false false false false false false false false
bool |= 0b00000101 // atribuo "true" para o primeiro e terceiro bit
console.log('primeiro bit é: ', (bool & 0b00000001) > 0) // true
console.log('segundo bit é: ', (bool & 0b00000010) > 0) // false
console.log('terceiro bit é: ', (bool & 0b00000100) > 0) // true
console.log('-----------------')
bool &= 0b11111110 // atribuo "false" para o primeiro bit
console.log('primeiro bit é: ', (bool & 0b00000001) > 0) // false
console.log('segundo bit é: ', (bool & 0b00000010) > 0) // false
console.log('terceiro bit é: ', (bool & 0b00000100) > 0) // true
console.log('-----------------')
Remembering:
- 0 & 0 => 0
- 0 & 1 => 0
- 1 & 0 => 0
- 1 & 1 => 1
- 0 | 0 => 0
- 0 | 1 => 1
- 1 | 0 => 1
- 1 | 1 => 1
What I do here is compare all 8 bits with other 8 bits. If I compare the byte 0b00000001
with bool
, and the first bit of bool
is also 1
, then the result will be 0b00000001
, that is, greater than 0
(0b00000000
), so the first bit of bool
is true
.