Most performant way to compare first 2 bytes (given a pointer) to fixed values?

StackOverflow https://stackoverflow.com/questions/19133998

  •  30-06-2022
  •  | 
  •  

Question

Given a pointer I want to compare the first two bytes to fixed values. data is a void pointer. Is there a "better" way than this:

unsigned char foo[] = {0xFF, 0x3B};
memcmp(data, foo, 2);

Maybe where I dont have to create a new char array? Thanks!

Was it helpful?

Solution

You should certainly try doing it using memcmp(), but if that creates overhead you can do it like @LS_dev suggested, although I would suggest doing explicit character accesses to avoid the endianness issue:

if(((unsigned char *) data)[0] == 0xff && ((unsigned char *) data)[1] == 0x3b)
{
}

of course, it would make sense to factor out the casting for a major clarity boost:

const unsigned char *chardata = data;
if(chardata[0] == 0xff && chardata[1] == 0x3b)
{
}

OTHER TIPS

EDIT: Due to some concerns regarding sizeof(char), memory alignment and compiler/library optimizations,

As a PLATFORM DEPENDENT alternative, this answer MAY HAVE better performance then memcmp:

Little endian (Intel byte-order):

if (*(short*)foo == 0x3bff) ...

Big endian (Network byte order):

if (*(short*)foo == 0xff3b) ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top