Question

I need to test if a file is a ELF file, to do this, i have to compare the first four bytes. The first bytes of the files begins with 0x7F 0x45 0x4C 0x46.

I use fread(...) to read first four bytes out to an array. Printing the content of the array shows that the file contains the hex numbers described over.

I have tried some easy methods to compare each byte with the hex code, like this

if(bytes[0] != "0x7f" || bytes[1] != "0x45 ....) printf("Error, not ELF file")

But as i understand, i cant compare bytes this way. Which way should i compare the content in the array to get this correct ?

Was it helpful?

Solution

The bytes you read are not strings, they are single bytes. So compare e.g. bytes[0] with 0x7f (the integer literal and not the string) or 127 decimal or 0177 octal.

OTHER TIPS

You certainly can't compare bytes that way; you're comparing a single character with the pointer to a string literal. Not a lot of right.

You just need to do:

if(bytes[0] != 0x7f || bytes[1] != 0x45 || /* more */)

Just make sure bytes is unsigned char.

You can also make it a bit more clear by using a function:

const unsigned char header[] = { 0x7f, 0x45, 0x4c, 0x46 };

if(memcmp(bytes, header, sizeof header) != 0)
{
  /* bad header */
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top