Bitwise enumeration

Hello forum,

The source that i am going through contains the following enumeration values

1
2
3
4
5
6
7
    enum SyncOperation
    {
        NO_SYNC     = 0x000,
        SYNC_DEVICE = 0x010,
        SYNC_HOST   = 0x001,
        SYNC_ARRAY  = 0x100,
    };


And there are several bitwise operation going on using the enumaration value. I am confused about this value like "0x000" . What does this "x" represent here?

Any reference to this issue?


Regards
Sajjad
The "0x" denotes the hexadecimal format for numbers.

http://en.wikipedia.org/wiki/Hexadecimal
it's hexadecimal digit, 2-digit hexadecimal digit representing 8-bit of binary data. take a look of this example:
1
2
3
4
5
6
7
8
#include <iostream>

int main() {
	int test = 0x31; //calculates: (3*161)+(1*160)
	std::cout << test << std::endl;
	std::cin.get();
	return 0;
}


result:
49


http://en.wikipedia.org/wiki/Hexadecimal
http://www.cplusplus.com/doc/hex/

CMIIW
What if i want get the print out in the same format as mentioned in the enumeration . If i issue the following statement :

 
cout << SYNC_DEVICE << endl;


I get 16 in the printout, i would like to see 0x010 instead.

Thanks
Sajjad
1
2
3
4
5
6
7
8
//you'll need to include <iomanip> for std::setfill() and std::setw()
std::cout << "0x" << std::hex << std::setfill('0') << std::setw(3) << SYNC_DEVICE << std::endl;

//or

//you'll need to include <cstdio> for printf()
printf("0x%.3x\n", SYNC_DEVICE); 
Last edited on
How the following if statement will be evaluated ?

1
2
3
4
5
6
7
8

unsigned int syncOp = SYNC_DEVICE;

if(syncOp & SYNC_DEVICE)
{
        .....................
        ....................
}



Thanks
Sajjad
& is the bitwise and operator. What this means is that each bit in syncOp is compared to the equivalent bit in SYNC_DEVICE. If that bit is set to 1 in both, then the resulting bit in the value that's returned is set to 1; otherwise, it is set to 0.

Since syncOp is already set to SYNC_DEVICE, then the bits in both those entities are set identically. This means that the result of (syncOp & SYNC_DEVICE) will by SYNC_DEVICE.

Furthermore, since this result is non-zero, the if statement will be true.

This is an example of using bit flags. A search for "bit flags C++" should get you some more information.
Last edited on
If the any of the evaluation of bit-wise operators end up inside the if(...) condition as the following :

if(0x000) - interpreted as false
if(0x111) - interpreted as true
if(0x001) - ?
if(0x011) - ?


The question marks are my confusion.
everything != 0 is iterpreted as true
Topic archived. No new replies allowed.