我有一個buffer[]
包括十六進制字節,我想搜索此緩衝區以查找特定字節。例如:以十六進制搜索特定字節
我的緩衝區有4096
字節,我想在這個搜索如果字節45 34 67 23
(在一起)在這個緩衝區內(像在緩衝區中搜索字符串)。
你有什麼想法我該怎麼做?編程語言是C
我有一個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 */
你也可以使用這個更快的版本。但是你必須記住,這隻適用於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)));
你也可以這樣做: int index =(int)((int64_t)ptrEndBuffer - ((int64_t)ptrStartBuffer + 1))/ /強制轉換,因爲如果在堆棧中工作(高地址)強制轉換爲int32_t可能會溢出整數並呈現爲負數 – DipSwitch 2011-05-10 12:34:27
你使用什麼語言? – Mat 2011-05-10 09:47:37
什麼語言?另外,最天真的實現有些問題嗎? (即找到值爲'45'的第一個字節,看看它是否跟着'34 67 23',如果不是,重複直到數組結束) – Piskvor 2011-05-10 09:47:58
我很抱歉,我忘了說它的C語言!聽起來不錯,也就是說謝謝:) – nomercy 2011-05-10 09:53:23