2013-04-15 75 views
0

我正在使用此功能,需要反轉一個。它將HEX(unicode)字符串轉換爲unicode(WideString)。我需要反向函數將其轉換回來,即Widestring回到HEX(unicode)。ConvertHexToWideString - 反轉功能

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; 
+0

我猜你錯過了鏈接[BinToHex]( http://docwiki.embarcadero.com/Libraries/XE3/en/System.Classes.BinToHex)在你找到'HexToBin'的幫助文件中。該鏈接是針對XE3文檔的,但它們基本相同,並且在頁面底部有一個代碼示例鏈接。 –

+0

謝謝肯,它幫助:)我只需要稍微修改它。你是老闆:) – Legionar

+0

你不能將'WideString'類型轉換爲'PAnsiChar'。首先將「WideString」類型轉換爲「指針」,然後將其類型轉換爲「PAnsiChar」。 –

回答

3

你根本相反的,使用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; 
+0

謝謝大家。 – Legionar