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.
The next step would involve loading the data (whether from file or database) into the Memory Stream using the method SaveToStream
end;Then, we use the Seek method which requires us to specify the origin offset which in our case would “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.
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;
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.