Compare byte in unsigned char with hex, test if file is ELF file

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 ?


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.

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 */

Need Your Help

Can't mock Date class

java unit-testing junit mocking mockito

i am using mockito and i have a custom date class and i want to be able to mock this date class in my test class, so i tried the following:

Populating C# ListView With Mysql Table

c# mysql listview

I don't understand why the listview is empty.