Search code examples
c++strcmpmemcmp

c++ best way to compare byte array to struct


I need help. I have an unsigned char * and say I have a struct

struct{
     int a=3;
     char b='d';
     double c=3.14;
     char d='e';
     } cmp;
unsigned char input[1000]; 
l= recv(sockfd,input , sizeof(cmp),0);

I want to compare cmp and input. What is the fastest way?

Thanks a lot in advance.


Solution

  • If the compiler guarantees that there are no gaps between fields in the struct (usually happen due to packing) or you can use a #pragna to cancel any such gaps, then you can compare by either:

    memcmp(&cmp, input, sizeof(stuct ThesSruct));
    

    Or, my preferred:

    cmp == *(struct TheStruct *)input // provided the struct doesn't contain pointers.
    

    But a much safer way would be to compare it on a field by field basis. And even more, prepare special functions for extracting ints, floats, etc.. from the raw input. For example, extracting an int at index n may be as simple as

    *(int *)&input[n]
    

    But it might be more complicated, like shifting chars at 8, 16, 24 bits.

    In short, accessing the communication data must be done with the most robust way, checking every basic element and not assuming anything.