c - 在文件的字符数组中搜索 2 个连续的十六进制值

标签 c arrays search pointers hex

我已经使用 fread 将一个文件读入一个字符数组。现在我想在该数组中搜索两个连续的十六进制值,即 FF 后跟 D9(它是一个表示文件结尾的 jpeg 标记)。这是我用来执行此操作的代码:

char* searchBuffer(char* b) {
    char* p1 = b;
    char* p2 = ++b;
    int count = 0;

    while (*p1 != (unsigned char)0xFF && *p2 != (unsigned char)0xD9) {
        p1++;
        p2++;
        count++;
    }

    count = count;
    return p1;
}

现在我知道如果我搜索不包含 0xFF 的十六进制值(例如 4E 后跟 46),此代码可以工作,但每次我尝试搜索 0xFF 时都会失败。当我不将十六进制值转换为 unsigned char 时,程序不会进入 while 循环,当我这样做时,程序会遍历数组中的所有字符,并且在出现越界错误之前不会停止。我很困惑,请帮忙。

忽略计数,它只是一个帮助我调试的变量。

提前致谢。

最佳答案

为什么不使用 memchr() 来查找潜在的匹配项?

此外,请确保您处理的是潜在签名类型的提升(char 可能已签名,也可能未签名)。请注意,虽然 0xff0xd9 将高位设置为 8 位值,但它们是非负整数常量,因此没有“符号扩展”发生在他们身上的事情:

char* searchBuffer(char* b) {
    unsigned char* p1 = (unsigned char*) b;
    int count = 0;

    for (;;) {
        /* find the next 0xff char */
        /* note - this highlights that we really should know the size   */
        /* of the buffer we're searching, in case we don't find a match */
        /* at the moment we're making it up to be some large number     */
        p1 = memchr(p1, 0xff, UINT_MAX);
        if (p1 && (*(p1 + 1) == 0xd9)) {
            /* found the 0xff 0xd9 sequence */
            break;
        }

        p1 += 1;
    }

    return (char *) p1;
}

另外,请注意,您确实应该传递正在搜索的缓冲区大小的一些概念,以防找不到目标。

这是一个接受缓冲区大小参数的版本:

char* searchBuffer(char* b, size_t siz) {
    unsigned char* p1 = (unsigned char*) b;
    unsigned char* end = p1 + siz;

    for (;;) {
        /* find the next 0xff char */
        p1 = memchr(p1, 0xff, end - p1);
        if (!p1) {
            /* sequnce not found, return NULL */
            break;
        }


        if (((p1 + 1) != end) && (*(p1 + 1) == 0xd9)) {
            /* found the 0xff 0xd9 sequence */
            break;
        }

        p1 += 1;
    }

    return (char *) p1;
}

关于c - 在文件的字符数组中搜索 2 个连续的十六进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6089805/

相关文章:

asp.net - 从 ASP.NET 应用程序调用时,编译的 C dll 无法设置指针

JavaScript toString 或 join 长数字数组 (SSN)

java - 如果有多个结果,数组的最低值

java - 在牛津词典中搜索

C 编程帮助 - 将值加在一起/for 循环

使用 Visual Studio 2012 是否会意外损坏系统文件或个人文件

javascript - 是否修改对象 : to use a variable, 中的数组的性能?

mysql - Sphinx 搜索引擎的首字母缩略词

c - 将列表和内部字典定义为c中字典的值

arrays - 如何使用 jq 过滤不在列表中的选择项?