411gi
411gi

Reputation: 17

#define as unsigned char

I would like to know how can I tell to compiler that a #define is an unsigned char. if #define 1 byte do this:

   #define AACEESS_PSS 0x80
    #define ACCESS_PSS  ((unsigned char)0x80)

but if #define has more byte what should to do?? for example:

 #define ACCESS_PSS {0x32,0xFD,0x6E,0x2D}

I need this cast for assign #define with unsigned char

int main(){
unsigned char ResponseData[100];
for (int i = 0; i <4;i++0){

                if (ResponseData[i+5]==ACCESS_PSS){ //how to do this???
                            cout<<5<<endl;
                                          }

ResponseData from programm get value and byte 5 to 8 is equal with ACCESS_PSS.

Upvotes: 0

Views: 1249

Answers (2)

myaut
myaut

Reputation: 11504

ResponseData[i+5]==ACCESS_PSS

You can't compare four unsigned chars with single equality operator in C.

You can convert to uint32_t, but it may break due to unaligned access or different endianness, i.e.:

#define ACCESS_PSS    0x32FD6E2D
...
if(*((uint32_t*) (ResponseData + i + 5)) == ACCESS_PSS) { /*...*/ }

The only clean way to do that is memcmp, or similiar function:

const unsigned char access_pss[4] = {0x32,0xFD,0x6E,0x2D};
...
if(memcmp(ResponseData + i + 5, access_pss, 4) == 0) { /*...*/ }

Upvotes: 3

Jens Gustedt
Jens Gustedt

Reputation: 78923

Since C99 we have compound literals for that:

#define ACCESS_PSS (unsigned char const[]){0x32,0xFD,0x6E,0x2D}

You can still use it as ACCESS_PSS[2] e.g.

The const in the definition allows the compiler to do optimisations, in particular it may avoid to have multiple copies of that array all over.

Upvotes: 0

Related Questions