Using the if condition I am trying to compare the buffer with the given jpg signatures, but I never find something. In GDB I just see the while looping, but never entering the if condition. What have I done wrong?

int block = 512;
int buffer[512];   

int signature[3] = {0xff, 0xd8, 0xff};
int signature_1   = 0xe1;
int signature_2   = 0xe0;

while (!feof(inptr))
        fread(&buffer, block, 1, inptr);

        if (buffer[0] == signature[0] && buffer[1] == signature[1] && buffer[2] == signature[2] && (buffer[3] == signature_1 || buffer[3] == signature_2)) 
               printf("found something \n");

buffer is an array of ints. on the appliance, an int is 4 bytes long. this means that the total size of your array is 512 * 4 = 2048 bytes not 512 (which you want) but that's not the actual problem.

the problem is that the 512 bytes that you're reading are not stored byte by byte into each element of the array. instead, the first 4 bytes are stored into the first element, the second 4 bytes are stored into the second element, and so on.

this means that if the first for bytes are 0xff, 0xd8, 0xff, and 0xe0, then buffer[0] typically stores 0xe0ffd8ff not only 0xff. similarly for buffer[1], buffer[2], and buffer[3] and therefore the condition is never met.

I'll leave the fix to you to think about. Feel free to ask for more hints in the comments though!

  • This answered my question. Now it's obvious. Thank you very much for this in-depth response! I used now char (which has 1B long memory size) and it works. But is there an other data type which is more suitable, or is char just OK? – Lex Jun 6 '15 at 16:06
  • @Lex given your approache, it wouldn't make much of a difference I think (it could cause problems with other approaches since the maximum value that can be represented with a char is 128(dec) or 0x80(hex) ). However, maybe it's more suitable to use uint32_t (defined in stdint.h) or unsigned char. – Kareem Jun 6 '15 at 16:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .