Recent

Author Topic: Working with binary files and searching for hex values  (Read 12507 times)

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: Working with binary files and searching for hex values
« Reply #15 on: January 02, 2018, 08:03:35 pm »
You just need to adapt the logic of the Locate function to suit your changed requirement.

Code: Pascal  [Select][+][-]
  1. program SearchBinary;
  2.  
  3. {$Mode objfpc}{$H+}
  4. {$IfDef windows}{$AppType console}{$EndIf}
  5.  
  6. uses sysutils, Classes;
  7.  
  8. type
  9.   T5ByteArray = array[0..4] of Byte;
  10.  
  11. const
  12.   ArrayToFind: T5ByteArray = (($9A), ($4E), ($0B), ($D7), ($40));
  13.   FileNameToSearch: String = 'test.bin';
  14.  
  15. var
  16.   fs: TFileStream;
  17.   fLength, p: Int64;
  18.   b: Byte;
  19.   found: Boolean = False;
  20.  
  21.   function Located: Boolean;
  22.   var
  23.     x: Integer;
  24.  
  25.       function ByteFound: Boolean;
  26.       begin
  27.         b:=fs.ReadByte;
  28.         Exit(b = ArrayToFind[x]);
  29.       end;
  30.  
  31.   begin
  32.     for x:=0 to 1 do
  33.       if not ByteFound then
  34.         Exit(False);
  35.     b:=fs.ReadByte; // ignore value of 3rd byte
  36.     for x:=3 to 4 do
  37.       if not ByteFound then
  38.         Exit(False);
  39.     Result:=True;
  40.   end;
  41.  
  42. begin
  43.   if not FileExists(FileNameToSearch) then begin
  44.     WriteLn('"',FileNameToSearch,'" could not be found');
  45.     WriteLn('Press [Enter] to quit');
  46.     ReadLn;
  47.     halt;
  48.   end
  49.   else begin
  50.     fs:=TFileStream.Create(FileNameToSearch, fmOpenRead);
  51.     fLength:=fs.Size;
  52.     try
  53.       p:=0;
  54.       while (p <= fLength - SizeOf(T5ByteArray)) do begin
  55.         fs.Position:=p;
  56.         if Located then begin
  57.           found:=True;
  58.           Break;
  59.         end
  60.         else begin
  61.           Inc(p);
  62.           if (p mod 1000) = 0 then
  63.             Write('.');
  64.         end;
  65.       end;
  66.     finally
  67.       fs.Free;
  68.     end;
  69.     if found then
  70.       WriteLn('Byte sequence found at position $',hexStr(p, 8))
  71.     else WriteLn('Byte sequence not found');
  72.     ReadLn;
  73.   end;
  74. end.

It would be worth googling for "regular expression", since Lazarus has a good implementation of regular expressions, and they give you far more flexibility in doing searches of this kind.
The code I showed is very specific for only one search - so not really useful except for learning Pascal.

guest61674

  • Guest
Re: Working with binary files and searching for hex values
« Reply #16 on: January 02, 2018, 08:07:23 pm »
in Linux ?

DumDum

  • New Member
  • *
  • Posts: 32
Re: Working with binary files and searching for hex values
« Reply #17 on: January 02, 2018, 08:12:55 pm »
using windows.

Howard, I tried what you implemented but it did not work.

EDIT. Never mind, error on my end it works :)

Last question and I am done bugging for the day.

What if I didn't wanted a user input of the file instead of assigning the file to:

 FileNameToSearch: String = 'test.bin';
 
I would like the 'test.bin' to be any file the user can select.




« Last Edit: January 02, 2018, 08:18:44 pm by CDuman »

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: Working with binary files and searching for hex values
« Reply #18 on: January 02, 2018, 08:31:21 pm »
Use the option Thaddy showed in his code: ParamStr(1)
This returns the first command line argument following your executable name as a string, and in this case we assume it is a proper filename with a fully qualified path.
You can test this in the Lazarus IDE using Run->Run Parameters...
This brings up a large dialog, but you can ignore (leave blank) all the edit boxes except "Command line parameters (without application name)".

In a GUI program you would use a TFileOpenDialog to pick the file, of course.

DumDum

  • New Member
  • *
  • Posts: 32
Re: Working with binary files and searching for hex values
« Reply #19 on: January 02, 2018, 09:17:39 pm »
Sorry Howard, you lost me there. 

What am I to write in the "Command line parameters (without application name)" section.

I am having difficulty understanding ParamStr(1)

Is there a way to incorporate that in the code that you have written already?

howardpc

  • Hero Member
  • *****
  • Posts: 4144
Re: Working with binary files and searching for hex values
« Reply #20 on: January 02, 2018, 11:06:59 pm »
You're on Windows, and may be unfamiliar with the command line interface from DOS days?
In Windows' Start Menu type "command" without the quotes.
You'll see  a list with sections headed Programs(x), Settings(y), Documents(z), etc where x, y, z is a count of the listings in each section.
Under Programs should be a line: Command Prompt.
Click on that.
You are now looking at a console (a black text-only window whose title should be Command Prompt).

In the console type "dir" (no quotes) and press Enter.
You'll see a list of files in the current directory (perhaps it is "C:\Users\CDuman")
You have given Windows the name of a (built-in) program called dir.

Now type dir /w (followed by Enter).
This gives Windows both the name of the program to run (dir), and a command line parameter (/w) which alters the display of the directory listing.

Likewise in the Lazarus IDE, if you type the path+name of the file you want to open as the only entry in the "Command line parameters" box, this will supply that parameter to your program when it runs. You might type C:\Users\yourusername\LazProjects\test.bin
or what ever the file is.
In your program this string is then picked up as ParamStr(1) (the 1 means it is the first parameter found on the commandline after the executable name)
. ParamStr(1) is just a string function. Treat it just like any other filename in this case.
Command line parameters are one of the few ways in which it is possible to supply variable data to your console program at the moment it starts executing.

If you run your program outside the IDE from a command prompt, you can give it a similar filename parameter as a string that follows the typed executable name.

jamie

  • Hero Member
  • *****
  • Posts: 6128
Re: Working with binary files and searching for hex values
« Reply #21 on: January 03, 2018, 12:14:24 am »
How large is this file?

The reason I ask is it may be able to all fit in memory and then it would be a simple task
and fast.
The only true wisdom is knowing you know nothing

DumDum

  • New Member
  • *
  • Posts: 32
Re: Working with binary files and searching for hex values
« Reply #22 on: January 03, 2018, 12:27:56 am »
The files will be up to 2048kb at maximum.

jamie

  • Hero Member
  • *****
  • Posts: 6128
Re: Working with binary files and searching for hex values
« Reply #23 on: January 03, 2018, 02:06:43 am »
Code: Pascal  [Select][+][-]
  1. Function FindMePartern(Ar:Array of Byte; FullFileName:String) :PtrInt;
  2. Var
  3.   M:TmemoryStream;
  4.   I:PtrInt;
  5. Begin
  6.   Result := -1; // Indicates failure;
  7.   Try
  8.    M := TMemoryStream.Create;
  9.    M.LoadFromFile(FullFileName);
  10.    Result := 0;
  11.   finally
  12.     If Result = -1 Then
  13.      Begin
  14.       M.Free; Exit;
  15.      end;
  16.    Result := -1;
  17.   End;
  18.   I := 0;
  19.   While ((I+Length(AR)) <= M.Size)and(Result = -1) Do
  20.    begin
  21.      if CompareMem(@Pbyte(M.Memory)[I],@Ar[0], Length(ar)) Then Result := I Else
  22.      Inc(I);
  23.    end;
  24.  If Result <> -1 Then // We found it...
  25.   Begin
  26.     // here is where we can decide what to do with it now that we found the search mark.
  27.   end;
  28.  M.Free;
  29. end;      

Something to look at..
If FineMePartern([$DF,$DF,$FF,$AA],SomeFIleName) > -1 Then Beep.
« Last Edit: January 03, 2018, 02:08:24 am by jamie »
The only true wisdom is knowing you know nothing

DumDum

  • New Member
  • *
  • Posts: 32
Re: Working with binary files and searching for hex values
« Reply #24 on: January 03, 2018, 03:17:20 am »
Is there a way to output hex on the screen from a decimal output?

Thaddy

  • Hero Member
  • *****
  • Posts: 14364
  • Sensorship about opinions does not belong here.
Re: Working with binary files and searching for hex values
« Reply #25 on: January 03, 2018, 08:03:41 am »
Use IntToHex or integer.ToHexString:
Code: Pascal  [Select][+][-]
  1. {$ifdef fpc}{$mode delphi}{$H+}{$I-}{$endif}
  2. uses sysutils;
  3. var i:integer =255;
  4.  
  5. begin
  6.   writeln(123.ToHexString(2));// literal
  7.   writeln(i.ToHexString(2)); // variable
  8.   writeln(IntToHex(i,2)); // function
  9. end.

I already gave some code to format it nicely here: http://forum.lazarus.freepascal.org/index.php/topic,39503.msg271324.html#msg271324
The DumpAsHex function does what you want and is re-usable; You can work from there.
« Last Edit: January 03, 2018, 08:13:17 am by Thaddy »
Object Pascal programmers should get rid of their "component fetish" especially with the non-visuals.

DumDum

  • New Member
  • *
  • Posts: 32
Re: Working with binary files and searching for hex values
« Reply #26 on: January 03, 2018, 08:54:01 am »
Thanks Thaddy,

I will try to digest this.  I am very new to Pascal and am having a bit of a hard time.

 

TinyPortal © 2005-2018