I’ve read a file into an array of characters using fread. Now I want to search that array for two consecutive hex values, namely FF followed by D9 (its a jpeg marker signifying end of file). Here is the code I use to do that:
char* searchBuffer(char* b) {
char* p1 = b;
char* p2 = ++b;
int count = 0;
while (*p1 != (unsigned char)0xFF && *p2 != (unsigned char)0xD9) {
p1++;
p2++;
count++;
}
count = count;
return p1;
}
Now I know this code works if I search for hex values that don’t include 0xFF (eg 4E followed by 46), but every time I try searching for 0xFF it fails. When I don’t cast the hex values to unsigned char the program doesn’t enter the while loop, when I do the program goes through all the chars in the array and doesn’t stop until I get an out of bounds error. I’m stumped, please help.
Ignore count, its just a variable that helps me debug.
Thanks in advance.
You are falling foul of integer promotions. Both operands for
!=(and similar) are promoted toint. And if at least one of them isunsigned, then both of them are treated asunsigned(actually that isn’t 100% accurate, but for this particular situation, it should suffice). So this:is equivalent to:
On your platform,
charis evidentlysigned, in which case it can never take on the value of(unsigned int)0xFF.So try casting
*p1as follows:Alternatively, you could have the function take
unsigned chararguments instead ofchar, and avoid all the casting.[Note that on top of all of this, your loop logic is incorrect, as pointed out in various comments.]