How to search in a BYTE array for a pattern?

后端 未结 4 1216
南旧
南旧 2021-01-04 09:02

I have a Byte array :

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

00FFFFFFFFFFFF0010AC4C4053433442341401030A2

4条回答
  •  無奈伤痛
    2021-01-04 09:42

    Here's a simple/naive solution using C buffers:

    const char *find_needle(const char *haystack, size_t haystack_length, const char *needle, size_t needle_length) {
        for (size_t haystack_index = 0; haystack_index < haystack_length; haystack_index++) {
    
            bool needle_found = true;
            for (size_t needle_index = 0; needle_index < needle_length; needle_index++) {
                const auto haystack_character = haystack[haystack_index + needle_index];
                const auto needle_character = needle[needle_index];
                if (haystack_character == needle_character) {
                    continue;
                } else {
                    needle_found = false;
                    break;
                }
            }
    
            if (needle_found) {
                return &haystack[haystack_index];
            }
        }
    
        return nullptr;
    }
    

    A more efficient solution would be using the Knuth-Morris-Pratt algorithm for example but the implementation is also more complex.

提交回复
热议问题