0

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!

tzippy
  • 6,458
  • 30
  • 82
  • 151

2 Answers2

1

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) ...
LS_ᴅᴇᴠ
  • 10,823
  • 1
  • 23
  • 46
1

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)
{
}
Community
  • 1
  • 1
unwind
  • 391,730
  • 64
  • 469
  • 606