Alright so for fun, I decided to try something a little different in my code. I created a union containing a 32-bit int and a struct containing four unsigned chars. I then read the first four bytes of card.raw and check if the 32-bit int is equal to either of the two possible headers. Then, I use fseek to move forward in the file 512 - the size of my union (4 bytes) forward and read it again. I wrapped all this in a do-while loop that would terminate when the first jpeg was found. I let it run for a while and 10 minutes later, still nothing. What am I missing here?

Here's the code:

 * recover.c
 * Computer Science 50
 * Problem Set 4
 * Recovers JPEGs from a forensic image.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>

typedef union  {
    struct {
        unsigned char byte1;
        unsigned char byte2;
        unsigned char byte3;
        unsigned char byte4;
    } bytes;
    uint32_t whole;
} jpeg_header;

int main(int argc, char* argv[])
    FILE *fp = fopen(argv[1], "r");
    if (fp == NULL) {
        return 1;
    jpeg_header header;

    do {
    fread(&header, sizeof(jpeg_header), 1, fp);
    printf("%X -- %X, %X, %X, %X\n", header.whole, header.bytes.byte4, header.bytes.byte3, 
           header.bytes.byte2, header.bytes.byte1);
    fseek(fp, 512 - sizeof(jpeg_header), SEEK_CUR);
   } while (header.whole != 0xffd8ffe0 && header.whole != 0xffd8ffe1);

1 Answer 1


The answer is that, x86 is little endian which means it stores the least significant digits first (for example the number one-thousand four hundred and ninety seven would be stored as 7941).

There's an answer over on Stack Overflow that addresses why. For more on endianness checkout the Wikipedia article.

Thus, I should be looking for 0xe0ffd8ff and 0xe1ffd8ff respectively

You must log in to answer this question.

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