Store multiple boolean States in only one bool variable [duplicate]

this question already has an answer here : How to connect a bit on a number? (1 response) Closed 11 months ago.

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

Author: pic, 2020-03-22

1 answers

Well, first that in c there is no type 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 next is not something unique to any language, it can be done in C or C++, here I do in JavaScript because it is possible to simulate on the site.

Using some logic and binary operators, you can compare the values of the bits 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, i.e., greater than 0 (0b00000000), so the first bit of bool is true.

 3
Author: user140828, 2020-03-22 05:38:39