Reputation: 3870
I have an unsigned int and a hex value. I want to be able to check if the unsigned int contains the hex value; e.g:
unsigned int reason = 0x80020002
#define MAJOR_ERROR_CODE 0x00020000
#define MINOR_ERROR_CODE 0x00000002
#define OPTIONAL_ERROR_CODE 0x80000000
Now as we can see, the variable reason has all of the three #define error code. I need to be able to detect the presence/absence of the hex Error Codes int the variable reason. How do I do it?
Edit 1 : Apologies all, I guess I posted a slightly different question when I tried to simplify it and post. What I have is a couple of Major, Minor and Optional Error codes - For Eg
#define MAJOR_ERROR_CODE_1 0x00020000
#define MAJOR_ERROR_CODE_2 0x00010000
#define MAJOR_ERROR_CODE_3 0x00070000
#define MINOR_ERROR_CODE_1 0x00000002
#define MINOR_ERROR_CODE_2 0x00000004
#define MINOR_ERROR_CODE_3 0x00000006
#define OPTIONAL_ERROR_CODE_1 0x80000000
#define OPTIONAL_ERROR_CODE_2 0x50000000
#define OPTIONAL_ERROR_CODE_3 0x30000000
Now my unsigned int is a combination of these three error codes. Each of these error codes have a unique string and depending on which one of these is present in my variable reason i need to generate the string.
Upvotes: 2
Views: 1788
Reputation: 1889
I am not sure if i got the question correct but looks like can check with & operation
e.g.
((reason & MAJOR_ERROR_CODE) != 0)
{
//Do what you want to do for MAJOR_ERROR_CODE
}
Upvotes: 0
Reputation: 7136
Something like so:
const bool isErrorCodeSet = reason & MAJOR_ERROR_CODE;
//...and so on
You can see this works basically by manual and operation:
80020002
& 00020000
------------
00010000
Upvotes: 0
Reputation: 34418
If these are single bit codes, it's as simple as
if ((reason & MAJOR_ERROR_CODE) != 0)
{
// this is a major error
}
However I suspect it's actually a mask, e.g.
#define MAJOR_ERROR_MASK 0x7fff0000
if ((reason & MAJOR_ERROR_MASK) == MAJOR_ERROR_CODE)
{
// this is a major error
}
Upvotes: 2
Reputation: 12515
By using the binary operator &
:
if(reason & MAJOR_ERROR_CODE)
{
// Do Major Error code...
}
if(reason & MINOR_ERROR_CODE)
{
// Do minor Error code...
}
if(reason & OPTIONAL_ERROR_CODE)
{
// Do Optional error code...
}
Upvotes: 3