Binary storage of characteristics

Dec 16, 2012 at 7:52pm
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?
Dec 17, 2012 at 1:01pm
This would probably do the job for you:
http://www.cplusplus.com/reference/bitset/bitset/

File reading-writing using this data structure is pretty much trivial.

If you need to do it by hand - use bitwise operators. Some example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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?
Topic archived. No new replies allowed.