Lukali
Lukali

Reputation: 343

How to check if char array combines to make certain consecutive list of chars?

For example, my char array may be something like...

char array[8] = {0x00,0x07, 0x28, 0xFF, 0xAF, 0x00, 0x00, 0x00, 0x71}

and I want to check whether char[2] to char[7] is equal to '28 FF AF 00 00 00' hex, how would I do that in the simplest way? I know I can check each element individually, but I wanted to know if I can somehow specify that I am searching for hex 28FFAF000000 within space char[2] to char[7].

Upvotes: 0

Views: 55

Answers (2)

Jarod42
Jarod42

Reputation: 217880

You might do something like:

constexpr char expected[] = {0x28, 0xFF, 0xAF, 0x00, 0x00, 0x00};

return std::equal(std::begin(expected), std::end(expected), array + 2);

Upvotes: 3

YSC
YSC

Reputation: 40100

With std::equal:

const bool equal = std::equal(array+2, array+8, "\x28\xff\xaf\x00\x00\x00");

std::equal(start1, end1, start2) compares element by element the two ranges [start1, end1) and [start2, <end2>) where <end2> is chosen so the two ranges have equal length.

If you're certain to only work with bytes, and if efficiency is important, and you've check that you're compiler doesn't optimize std::equal away, you can use the C-ism std::memcmp:

const bool equal = (0 == std::memcmp(array+2, "\x28\xff\xaf\x00\x00\x00", 6));

Upvotes: 3

Related Questions