Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Name: Dr. Nick
Hey all,
I'm working with some binary files, and one of the things I'm trying to do is locate the position(s) of various hex values in the file.
What I've got so far is an array of BYTES, the same size as the file I'm working with. Is there any built in MFC or C++ function that will allow me to say, "find this hex string in the array"? If not, is there a better way to handle this data?
I could write my own, but I'd rather use something that's already been written if possible. I'm doing this within an MFC app, so that's all available, and I'm doing reading/writing with CFile.
Thanks.

Just to clarify:
If I have an array:
byte haystack[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Is there a way to find the index where a set value might start? Something like:
byte needle[] = {4, 5, 6, 7};
int offset = find(&haystack, &needle);
// or something like: find(&haystack, 4567);
ASSERT(offset == 4);Thanks again.

Well, I never did find either a library function or API that would do this (and after doing so I hope there really isn't one...), so here's what I ended up with:
template<typename T> int SubArray(T *haystack,
DWORD sizeofHaystack,
T *needle,
DWORD sizeofNeedle,
DWORD startOffset)
{
bool foundIt = false;
DWORD i;if (startOffset > sizeofHaystack || sizeofNeedle > sizeofHaystack)
return -1;
for (i=startOffset; i < sizeofHaystack &&
(sizeofHaystack - i) >= sizeofNeedle &&
!foundIt;
i++)
if (haystack[i] == needle[0])
{
foundIt = true;
for (DWORD j=0; j<sizeofHaystack && j<sizeofNeedle; j++)
if (haystack[i+j] != needle[j])
{
foundIt = false;
break;
}
}
return foundIt ? (i-1) : -1;
}You can use pretty much any data type for this, anything that is either a primitive type or any classes that have the == operator overloaded. It returns the index of the first element where the first match is found, or -1 if no match exists. For example:
int haystack[] = {1, 2, 3, 4, 5};
int needle[] = {3, 4};int i = SubArray(haystack,
sizeof(haystack) / sizeof(int),
needle,
sizeof(needle) / sizeof(int),
0);ASSERT(i == 2);
Works for me, and I tried it with ints, chars, bytes, CStrings, and a custom class I have. Hope I didn't do anything terribly wrong :)

![]() |
Row Number
|
C programming
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |