Hero Stradivari
Hero Stradivari

Reputation: 595

Comparing Arrays in C

Was wondering if there's a way to compare a set of data inside an array all at once. I'm currently making a JPEG image recovery program from a homework, I hard coded the JPEG byte pattern and it looks a bit messy.

It would really help me if I can gather suggestions on how to tidy this code up. The problem starts in the if condition inside the while loop.

The byte pattern that I want to check is 0xff 0xd8 0xff 0xe0 or 0xff 0xd8 0xff 0xe1

#define BLOCKSIZE 512

typedef uint8_t BYTE;

int main(int argc, char* argv[])
{
    // create a buffer of 512 Bytes
    BYTE buffer[BLOCKSIZE];

    // open card, check if fopen is successful 
    FILE* card = fopen("card.raw", "r");
    if (card == NULL)
    {
        printf("Failed to open card.\n");
        return -1;
    }

    // scan through card, 1 block at a time (512 Bytes) until end of file
    while (fread(&buffer, BLOCKSIZE, 1, card) == 1)
    {
        // read current buffer
        fread(&buffer, BLOCKSIZE, 1, card);

        // check if current buffer marks the start of a JPEG pattern
        if ((buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] == 0xe0) ||
            (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && buffer[3] == 0xe1))

    }
}

Upvotes: 0

Views: 144

Answers (2)

ianks
ianks

Reputation: 1768

Is using a byte array necessary here? Since you are checking 4 bytes, you could use a uint32_t buffer[BLOCKSIZE / 4]

From there, you need to make sure fread() is reading int-wise.

fread(&buffer, sizeof(uint32_t), 1, card); // untested code

Then you check: if buffer[0] == 0xffd8ffe0 || **I'll leave this as an exercise to the reader**

Also, calling fread() twice might not have the behavior you are expecting.

Upvotes: 1

Scott Hunter
Scott Hunter

Reputation: 49920

You could simplify this a bit:

if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3]&0xfe) == 0xe0))

That is, combine the common parts, and use a mask to hide the bit you don't care about when checking buffer[3].

You can also use memcmp to compare 2 different blocks of memory (in your case, one would be the run you want to test against).

Upvotes: 1

Related Questions