suryakantb 0 Newbie Poster

Hi,

I am sharing a tips on "Identifying Files From Their first 4 Bytes Or Magic Numbers" related to Delphi

Sometime back I faced the task of having my application take file data from stream and save them on disk in their original format. Now, the tricky part was that the file information had not been stored externally,all there was, was the raw data! At that point in time the task at hand seemed to me something like recognizing .chk files that Chkdsk/Scandisk creates from lost file fragments. But my application was not a data-recovery or a forensic program! i was looking for something simple and then it was there right in front of me (and in file data!) All i needed to do, was check the file's magic number and match it with magic number of popular file formats.
The first four bytes of a file contain the file signatures or the magic numbers that 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 WORD datatype 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


Hope you find this tips useful and of assistance.

Thanks,
Suryakant

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.