【问题标题】:search in HEX for specific bytes以十六进制搜索特定字节
【发布时间】:2011-05-10 09:42:37
【问题描述】:

我有一个buffer[],包括十六进制字节,我想搜索这个缓冲区以查找特定字节。例如:

我的缓冲区有 4096 字节,如果字节 45 34 67 23(一起)在此缓冲区内(就像在缓冲区中搜索字符串),我想在其中搜索。

你知道我该怎么做吗?编程语言是 C。

【问题讨论】:

  • 什么语言?此外,最幼稚的实现是否存在某种问题? (即找到值为45的第一个字节,看看它后面是否有34 67 23,如果没有,重复直到数组结束)
  • 对不起,我忘了说它是针对 C 语言的!听起来不错,即谢谢你:)
  • @Paul 他的缓冲区可能包含 0x0 个字节?
  • @RedX: 好点 - 如果是 GNU/Linux 则有 memmem

标签: c search byte buffer hex


【解决方案1】:

只是“蛮力”它:)

haystacklen = 4096;
needlelen = 4;

foundat = -1;
index = 0; /* start at a different number if searching for 2nd occurrence */
while (index < haystacklen - needlelen + 1) {
    if ((buffer[index + 0] == 45)
     && (buffer[index + 1] == 34)
     && (buffer[index + 2] == 67)
     && (buffer[index + 3] == 23))
    {
        foundat = index;
    }
    index++;
}
/* foundat has the index of the 1st search bytes or -1 */

【讨论】:

  • “当有疑问时,使用蛮力”——肯·汤普森
  • 不应该是while (index &lt; haystacklen - needlelen)吗?
  • @Paul R:那就是while (index &lt;= haystacklen - needlelen)。假设它们的长度相同:haystacklen - needlelen 将是 0,而index 从 0 开始,循环将永远不会运行。
【解决方案2】:

您也可以使用这个更快的版本。但是您必须记住,由于 MAKEDWORD 宏,这仅适用于 x86 / little endian 处理器。

#define MAKEDWORD(a,b,c,d) ((uint32_t) (((uint32_t)a) & 0xFF) | ((((uint32_t)b) & 0xFF) << 8) | ((((uint32_t)c) & 0xFF) << 16) | ((((uint32_t)d) & 0xFF) << 24))
#define NEEDLE (MAKEDWORD(45,34,67,23))

// get the start and end address of the buffer
uint8_t *ptrEndBuffer = ((uint8_t*)buffer) + (4096 - sizeof(NEEDLE));
uint8_t *ptrStartBuffer = (uint8_t*)buffer - 1; // subtract -1 because we also want to get index 0

// while the result is not 0 we are good
while (ptrEndBuffer - ptrStartBuffer) {
    if ((*(uint32_t*)ptrEndBuffer) == NEEDLE) // get an whole integer instead of just one char
        break; // leave the loop if we found a match

    ptrEndBuffer--;
}

// the index will be -1 if we couldn't find a match else we subtract the start address + the 1 we first removed from the end buffer
int index = ((ptrEndBuffer == ptrStartBuffer) ? (-1) : (ptrEndBuffer - (ptrStartBuffer + 1)));

【讨论】:

  • 你也可以这样做: int index = (int)((int64_t)ptrEndBuffer - ((int64_t)ptrStartBuffer + 1)) // 转换为 long 因为如果在堆栈中工作(高地址)强制转换为 int32_t 可能会溢出整数并使其为负数
猜你喜欢
  • 2022-12-12
  • 1970-01-01
  • 2015-08-08
  • 2017-09-13
  • 2020-11-11
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多