I'm writing a program that is basically a 20Q game. I need to store characteristics as binary numbers in a text file where each digit represents a different characteristic, but I'm not sure how to go about it. Anyone know how to manipulate certain digits with Boolean expressions then read them digit by digit?
std::string s = "1101";
int num = 0;
int base = 1;
for (size_t i = 0; i < s.size(); ++i) {
num |= (s[i] - '0') * base;
base <<= 1;
}
// Access characteristic number 3
if (num & (1 << 3)) {
// characteristic number 3 is '1'
}
// Clear characteristic number 3
num &= ~(1 << 3);
// Set characteristic number 3
num |= 1 << 3;
// etc.
Some things to think of: do you really need to store these characteristics as bits? How many of them are there? Will these characteristics always be booleans? Maybe you should go for a more flexible way of storing?