How to use formatting flags?
By formatting flags I mean using the | bitwise operator to input several options to a function like C++ file I/O where you use something like file.open("f.txt",ios::in|ios::ate|ios::trunc). I'm wondering how I could use these myself. I was experimenting with it quite a bit and don't really see how it's possible.
Like unsigned int mode = (2|3|7); gets you 7...
And unsigned int mode = (2|7); also gets you 7.
So I don't really see how, in any way bitwise operators could really seperate them for you after being OR'd. Could anyone please shed some light on this? Thanks. :)
-Aternus
Your example doesn't work because 2 and 3 share a bit. For this method to work each option must be a power of two.
Each bit represents a certain option.
In hex:
To use:
Therefore, for a 16-bit number you can have a maximum of 16 options, because each bit has to be mutually exclusive. This is opposed to using normal enumerations where each separate number gives you an option, so a 16-bit integer can hold 2^16 values.
Each bit represents a certain option.
0000000000000001 - thrusters on0000000000000010 - shield on0000000000000100 - boost on
In hex:
#define THRUSTER_ON 0x0001#define SHIELD_ON 0x0002#define BOOST_ON 0x0004
To use:
activate( THRUSTER_ON | SHIELD_ON );// passes 16-bit integer 0000000000000011 which has the options set
Therefore, for a 16-bit number you can have a maximum of 16 options, because each bit has to be mutually exclusive. This is opposed to using normal enumerations where each separate number gives you an option, so a 16-bit integer can hold 2^16 values.
You need to use powers of 2 for your numbers.
Maybe an example program will help.
Maybe an example program will help.
#include <iostream>using namespace std;const unsigned int bit0 = 1;const unsigned int bit1 = 2;const unsigned int bit2 = 4;const unsigned int bit3 = 8;const unsigned int bit4 = 16;const unsigned int bit5 = 32;const unsigned int bit6 = 64;const unsigned int bit7 = 128;//etcvoid printbits(const unsigned int flags){ if (flags&bit0) cout << "bit0 "; if (flags&bit1) cout << "bit1 "; if (flags&bit2) cout << "bit2 "; if (flags&bit3) cout << "bit3 "; if (flags&bit4) cout << "bit4 "; if (flags&bit5) cout << "bit5 "; if (flags&bit6) cout << "bit6 "; if (flags&bit7) cout << "bit7 "; cout << endl;}int main(int argc, char *argv[]){ printbits(bit6|bit3|bit1); return 0;}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement