поиск в HEX для конкретных байтов - PullRequest
0 голосов
/ 10 мая 2011

У меня есть buffer[], включая шестнадцатеричные байты, и я хочу найти этот буфер, чтобы найти определенные байты.Например:

Мой буфер имеет 4096 байтов, и я хочу найти в нем, если байты 45 34 67 23 (вместе) находятся внутри этого буфера (как поиск строки в буфере).

Ты хоть представляешь, как я могу это сделать?Язык программирования - C.

Ответы [ 2 ]

1 голос
/ 10 мая 2011

Просто "грубая сила" это:)

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 */
0 голосов
/ 10 мая 2011

Вы также можете использовать эту более быструю версию.Но вы должны помнить, что это работает только для процессоров x86 / little-endian из-за макроса MAKEDWORD.

#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)));
...