ConvertHexToWideString - 反向函数

时间:2013-04-15 22:14:27

标签: delphi-7

我正在使用此功能,需要反向功能。它将HEX(unicode)字符串转换为unicode(WideString)。我需要反向函数将其转换回来,即Widestring回到HEX(unicode)。

function _ConvertHexToWideString(AHex: AnsiString): WideString;
var wBinaryStream: TMemoryStream;
begin

  try
    wBinaryStream := TMemoryStream.Create;

    try
      wBinaryStream.Size := Length(AHex) div 2;

      if wBinaryStream.Size > 0 then
        HexToBin(PAnsiChar(AHex), wBinaryStream.Memory, wBinaryStream.Size);
    except
    end;
    SetString(Result, 
              PWideChar(wBinaryStream.Memory), 
              wBinaryStream.Size div SizeOf(WideChar));
  finally
    FreeAndNil(wBinaryStream);
  end;
end;

1 个答案:

答案 0 :(得分:4)

您只需反而使用BinToHex(),例如:

function _ConvertWideStringToHex(AStr: WideString): AnsiString;
var
  wBinaryStream: TMemoryStream;
  iBufSize: Integer;
begin
  try
    wBinaryStream := TMemoryStream.Create;
    try
      iBufSize := Length(AStr) * SizeOf(WideChar);
      wBinaryStream.Size := iBufSize * 2;
      if iBufSize > 0 then
        BinToHex(PAnsiChar(Pointer(AStr)), PAnsiChar(wBinaryStream.Memory), iBufSize);
    except
    end;
    SetString(Result, 
              PAnsiChar(wBinaryStream.Memory), 
              wBinaryStream.Size div SizeOf(AnsiChar));
  finally
    FreeAndNil(wBinaryStream);
  end;
end;

可以简化为:

function _ConvertWideStringToHex(AStr: WideString): AnsiString;
var
  iBufSize: Integer;
begin
  iBufSize := Length(AStr) * SizeOf(WideChar);
  if iBufSize > 0 then begin
    SetLength(Result, iBufSize * 2);
    BinToHex(PAnsiChar(Pointer(AStr)), PAnsiChar(Result), iBufSize);
  end else
    Result := '';
end;