簡體   English   中英

在十六進制中搜索特定字節

[英]search in HEX for specific bytes

我有一個包含HEX字節的buffer[] ,我想搜索此緩沖區以查找特定的字節。 例如:

我的緩沖區有4096個字節,如果字節45 34 67 23 (一起)位於此緩沖區內(例如在緩沖區中搜索字符串),我想在其中進行搜索。

你知道我該怎么做嗎? 編程語言是C。

只是“強力”就可以了:)

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 */

您也可以使用這個更快的版本。 但您必須記住,由於MAKEDWORD宏,此方法僅適用於x86 /小端序處理器。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM