I'm trying to search through a chunk of memory for a 4 byte hex value (0xAABBAABB) and then copy out the 4 bytes before that into a separate variable.
0xAABBAABB is the message terminator and I'm after the 4 bytes that precede this.
I'm given the start of the location of the data in memory from a *uint8_t and a message size. So the *uint8 holds the first 2 bytes of the message.
Any Help would be appreciated.
Thanks
Try something like this:
uint8_t *msg = ...;
int msgsize = ...;
...
uint8_t bytes[4];
bool found = false;
msg += 4;
msgsize -= 4;
while (msgsize >= 4)
{
if (*(uint32_t*)msg == 0xAABBAABB)
{
memcpy(bytes, msg-4, 4);
found = true;
break;
}
++msg;
--msgsize;
}
Or this:
uint8_t *msg = ...;
int msgsize = ...;
...
const uint8_t term[4] = {0xAA, 0xBB, 0xAA, 0xBB};
uint8_t bytes[4];
bool found = false;
msg += 4;
msgsize -= 4;
while (msgsize >= 4)
{
if (memcmp(msg, term, 4) == 0)
{
memcpy(bytes, msg-4, 4);
found = true;
break;
}
++msg;
--msgsize;
}