我已经使用 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
可能已签名,也可能未签名)。请注意,虽然 0xff
和 0xd9
将高位设置为 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/