Store multiple boolean states in only one bool variable

Asked

Viewed 110 times

1

The guy bool so much at C as in C++ consumes at least 1 byte of memory to be stored, I saw that this is because it needs to be addressed or something. So, it would be like this 1 byte to store more than one boolean state since true/false would only need 1 bit?

1 answer

3


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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.