I need a way to search through a block of memory for a char[2] array
"DA" using a pointer to a short. Ideally I would like to write
something like:
short *data = ... some data...;
int j = 0;
while( data[j] != *((short*) "DA") ) j++;
But this doesn't work. The char[2] obviously has an equivalent 16-bit
value so how do I get that info in a simple way?
Can the constant occur on an odd boundary? e.g., if the array had
XDAYDA
then would you want the match at character offset 1, or the one
at character offset 4?
If you need to find the ones on odd boundaries but were hoping to
compare characters two at a time instead of one at a time, then
you will not be able to do it simply by incrementing a byte at a time
but comparing two characters as a short, as many systems have alignment
requirements that do not allow shorts to be located on odd byte boundaries.
If you do want to search on odd boundaries, then here is a simple
algorithm that can make it more efficient:
unsigned char *datachar = (char *) data;
size_t j = 0, maxj = SIZE_OF_DATA_ARRAY;
while (j < maxj-1) {
if (datachar[j+1] == 'A') {
if (datachar[j] == 'D')
break;
} else if (datachar[j+1] == 'D') {
j++;
} else {
j += 2;
}
}
That is, if the next character ahead is not an 'A', there is no
point in checking the current character for 'D' -- either it
isn't a 'D' at all, or it isn't a "useful" 'D' because it isn't
followed by 'A'.