Search code examples
delphidelphi-7

Hex to Binary convert


I have converted my jpeg file as HEX code through hex converter.

Now how to convert that hex to binary and save as Jpeg file on disk.

Like:

var declared as Hex code and then convert that var hex code to binary and save on disk ?

Edit:

Var 
  myfileHex := 'FAA4F4AAA444444'; // long as HEX code of my JPEG 

function HexToBin(myfileHex): string;
begin    
  // Convert Hex to bin and save file as...
end; 

Solution

  • Delphi already has HexToBin (Classes) procedure, since at least D5.
    Try this code:

    procedure HexStringToBin;
    var
      BinaryStream: TMemoryStream;
      HexStr: AnsiString;
    begin
      HexStr := 'FAA4F4AAA44444';
      BinaryStream := TMemoryStream.Create;
      try
        BinaryStream.Size := Length(HexStr) div 2;
        if BinaryStream.Size > 0 then
        begin
          HexToBin(PAnsiChar(HexStr), BinaryStream.Memory, BinaryStream.Size);
          BinaryStream.SaveToFile('c:\myfile.bin')
        end;
      finally
        BinaryStream.Free;
      end;
    end;
    

    The same could be done with any binary TStream e.g. TFileStream.