Hex to Binary convert

12,274

Solution 1

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.

Solution 2

Hex is very easy to decode manually:

procedure HexToBin(const Hex: string; Stream: TStream);
var
  B: Byte;
  C: Char;
  Idx, Len: Integer;
begin
  Len := Length(Hex);
  If Len = 0 then Exit;
  If (Len mod 2) <> 0 then raise Exception.Create('bad hex length');
  Idx := 1;
  repeat
    C := Hex[Idx];
    case C of
      '0'..'9': B := Byte((Ord(C) - '0') shl 4);
      'A'..'F': B := Byte(((Ord(C) - 'A') + 10) shl 4);
      'a'..'f': B := Byte(((Ord(C) - 'a') + 10) shl 4);
    else
      raise Exception.Create('bad hex data'); 
    end; 
    C := Hex[Idx+1];
    case C of
      '0'..'9': B := B or Byte(Ord(C) - '0');
      'A'..'F': B := B or Byte((Ord(C) - 'A') + 10);
      'a'..'f': B := B or Byte((Ord(C) - 'a') + 10);
    else
      raise Exception.Create('bad hex data'); 
    end; 
    Stream.WriteBuffer(B, 1);
    Inc(Idx, 2);
  until Idx > Len;
end;

begin
  FStream := TFileStream.Create('myfile.jpg', fmCreate);
  HexToBin(myFileHex, FStream);
  FStream.Free;
end;
Share:
12,274
user1023395
Author by

user1023395

Updated on June 04, 2022

Comments

  • user1023395
    user1023395 almost 2 years

    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;