How to search in a BYTE array for a template?

I have an array of bytes:

BYTE Buffer[20000]; This array contains the following data:

00FFFFFFFFFFFF0010AC4C4053433442341401030A2F1E78EEEE95A3544C99260F5054A54B00714F8180B30001010101010101010121399030621A274068B03600DA281100001000000000000000000003000000003000000000000300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

My question is: how can I find this array for a template like " 000000FC "? I really don't think this is important, but I need an index where I can find my template too. Can anyone provide an example for this because I really don't understand this :(

+6
source share
3 answers

Since you are in C ++, do it in a C ++ way:

 char a[] = { 0, 0, 0, 0xFC }; char Buffer[20000] = ... std::string needle(a, a + 4); std::string haystack(Buffer, Buffer + 20000); // or "+ sizeof Buffer" std::size_t n = haystack.find(needle); if (n == std::string::npos) { // not found } else { // position is n } 

You can also use the algorithm to search for the array directly:

 #include <algorithm> #include <iterator> auto it = std::search( std::begin(Buffer), std::end(Buffer), std::begin(a), std::end(a)); if (it == std::end(Buffer)) { // not found } else { // subrange found at std::distance(std::begin(Buffer), it) } 

Or, in C ++ 17, you can use a string view:

 std::string_view sv(std::begin(Buffer), std::end(Buffer)); if (std::size_t n = sv.find(needle); n != sv.npos) { // found at position n } else { // not found } 
+23
source

You want something like memmem (this code is licensed by the GPL).

However, it should not be difficult to roll. As with the memmem implementation, you need a loop that memchr uses to find the first character of your needle in the haystack and memcmp to check every hit and see if you have your whole needle.

+6
source

Try this, just need:

 // Returns a pointer to the first byte of needle inside haystack, static uint8_t* bytes_find(uint8_t* haystack, size_t haystackLen, uint8_t* needle, size_t needleLen) { if (needleLen > haystackLen) { return false; } uint8_t* match = memchr(haystack, needle[0], haystackLen); if (match != NULL) { size_t remaining = haystackLen - ((uint8_t*)match - haystack); if (needleLen <= remaining) { if (memcmp(match, needle, needleLen) == 0) { return match; } } } return NULL; } 
+1
source

Source: https://habr.com/ru/post/896708/


All Articles