在二进制数据中搜索文本 [英] Searching text in binary data

查看:50
本文介绍了在二进制数据中搜索文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含文本的二进制数据.文字是已知的.搜索该文本的快速方法是什么:

I've a binary data which contains a text. The text is known. What could be a fast method to search for that text:

作为一个例子.

这是文字 1---!@##$%%#^%&!%^$!<= 假设这一行是 3 MB 的二进制数据现在,这是文本 2 ---!@##$%%#^%&!%^$!<= 假设这一行是 2.5 MB 的二进制数据这是文字 3 ---

This is text 1---
!@##$%%#^%&!%^$! <= Assume this line is 3 MB of binary data
Now, This is text 2 ---
!@##$%%#^%&!%^$! <= Assume this line is 2.5 MB of binary data
This is text 3 ---

如何搜索文本这是文本2.

目前我正在做:

size_t count = 0;
size_t s_len = strlen("This is text 2");

//Assume data_len is length of the data from which text is to be found and data is pointer (char*) to the start of it.
for(; count < data_len; ++count)
{
    if(!memcmp("This is text 2", data + count, s_len)
    {
         printf("%s\n", "Hurray found you...");
    }
}

  • 有没有其他更有效的方法来做到这一点
  • 将用 memchr('T') logic 替换 ++count 逻辑 help <= 如果此语句不清楚,请忽略
  • memchr 的一般情况下 big-O 复杂度应该是多少
  • 推荐答案

    标准 C 中没有任何东西可以帮助您,但有一个 GNU 扩展 memmem() 这样做:

    There's nothing in standard C to help you, but there is a GNU extension memmem() that does this:

    #define TEXT2 "This is text 2"
    
    char *pos = memmem(data, data_len, TEXT2, sizeof(TEXT2));
    
    if (pos != NULL)
        /* Found it. */
    

    如果您需要可移植到没有此功能的系统,您可以采用 memmem()glibc 实现并将其合并到您的程序中.

    If you need to be portable to systems that don't have this, you could take the glibc implementation of memmem() and incorporate it into your program.

    这篇关于在二进制数据中搜索文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆