0

我正在使用此功能,需要反向功能。它将 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;
4

1 回答 1

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;
于 2013-04-15T23:10:52.700 回答