Home  >  Q&A  >  body text

c++ - How to determine if two variables are equal

  1. Pointer variable PVOID lpbuffer points to a memory address,

  2. Variable GUID g = {0x25a207b9,0xddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}};

How to determine whether the content pointed to by the pointer lpbuffer is equal to the GUID?

给我你的怀抱给我你的怀抱2652 days ago1304

reply all(3)I'll reply

  • typecho

    typecho2017-06-17 09:17:56

    According to the definition of GUID structure on MSDN

    typedef struct _GUID {
      DWORD Data1;
      WORD  Data2;
      WORD  Data3;
      BYTE  Data4[8];
    } GUID;

    GUID is a structure that does not have an overloaded == operator, so if you want to compare two GUIDs, you must either implement the == operator or honestly compare the member variables one by one.

    // PVOID lpbuffer;
    // GUID g = {0x25a207b9,0xddf3,0x4660,{0x8e,0xe9,0x76,0xe5,0x8c,0x74,0x06,0x3e}};
    GUID *p = (GUID*)lpbuffer;
    BOOL flag = FALSE;
    if ((*p->Data1 == g.Data1)
        && (*p->Data2 == g.Data2)
        && (*p->Data3 == g.Data3)){
        flag = TRUE;
        for(int i; i < 8; i++){
           if (*p->Data4[i] != g.Data4[i]){
               flag = FALSE;
           }
        }
    }
    
    // flag变量为比较结果

    reply
    0
  • 学习ing

    学习ing2017-06-17 09:17:56

    There are two situations:

    The addresses are different, assuming that the GUID type overloads the == operator

    if (lpbuffer != &g && *(*GUID)lpbuffer == g) {}  // *为取值符,判断指针指向地址存放的值是否等于变量g

    The address is the same and the number of bytes is the same

    if (lpbuffer == &g && sizeof(*lpbuffer) == sizeof(g)) {} // &为取地址符,判断指针是否指向变量g的地址

    As for the GUID type that does not overload the == operator but knows its internal structure, you can refer to the answer of other respondent @一代Key客

    The GUID type has not overloaded the == operator and does not know its internal structure. I think it can be compared byte by byte

        if (sizeof(*lpbuffer) != sizeof(g)) return false;
        size_t size = sizeof(*lpbuffer);
        size_t i = 0;
        char* p1 = (char*)lpbuffer;
        char* p2 = &g;
        while ( i != size ) {
            if (*p1 != *p2) return false;
            p1++;
            p2++;
            i++;
        }
        return true;

    reply
    0
  • ringa_lee

    ringa_lee2017-06-17 09:17:56

    if (memcmp(lpbuffer, GUID, 16) == 0) {
        ...
    }

    reply
    0
  • Cancelreply