简体   繁体   中英

Bit manipulation Hexadecimal C++

I have an unsigned int and a hex value. I want to be able to check if the unsigned int contains the hex value; eg:

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.

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...    
}

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, eg

 #define MAJOR_ERROR_MASK 0x7fff0000
 if ((reason & MAJOR_ERROR_MASK) == MAJOR_ERROR_CODE)
 {
      // this is a major error
 }

You are most likely looking for bitwise-AND

C++ info here

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

I am not sure if i got the question correct but looks like can check with & operation

eg

 ((reason & MAJOR_ERROR_CODE) != 0) { //Do what you want to do for MAJOR_ERROR_CODE } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM