Identifying Files From Their first 4 Bytes Or Magic Numbers

The first four bytes of a file contain the file signatures or the magic numbersthat uniquely identify the file. For instance, a  JPEG image file is always found to hold the value FF D8 FF E0 (Hex) in the first four bytes, GIF image file is identified by its first three bytes as 47 49 46 and  42 4D as the first two bytes of the file indicates a Bitmap. This magic number can be used to determine the format of the file even if the system doesn’t identify it or in circumstances where you would want to strictly ensure that the file you are dealing with indeed belongs to the particular format.    

 Let’s create a small program, using Delphi,to accomplish this task. Declare two variables that we are going to to use hold value temporarily as WORDdatatype to make sure that only 2 bytes are copied from the stream.
var
val1,val2:  WORD;
The next step would involve loading the data (whether from file or database) into the Memory Stream using the method SaveToStream

var
val1,val2:  WORD;
MemStream:TMemoryStream;

begin Image1.SaveToStream(MemStream); ….

end;

Then, we use the Seek method which requires us to specify the origin offset which in our case would “soFromBeginning“.

MemStream.Seek(0, soFromBeginning); 

Call the Read method to copy the bytes to the variable.Since the cursor is placed at the beginning, we copy the first 2 bytes to val1.

MemStream.Read(val1,2); 

The cursor position should now be placed at 2, so next you need to Read the next 2 bytes to val2 but not taking any chances we can set the cursor position to 2.

MemStream.Position := 2;  MStream.Read(val2,2);

 We now have the first 4 bytes copied into variables but before proceeding further, i think it would be pertinent to remind that Intel machines use Endian format to read which means that Intel machines read the bytes backward. So while matching the values with magic numbers of popular file formats we will have to read them backwards. For instance $4749 becomes $4947.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!