I am using Delphi 2010 and I have a need to be able to convert a string to a hexadecimal string, and then later be able to convert that hexadecimal string back to the original unicode string.
For example, my string is: Михаи́л Васи́льевич Ломоно́сов
I was able to use Warren P’s StringToHex16 snippet here (and I pasted Warren’s snippet below) to convert the string to a hex string, but I don’t know how to convert that hex string back to the original unicode string.
function StringToHex16(str: string): string;
var
i:integer;
s:string;
begin
s:='';
for i:=1 to length(str) do begin
s:=s+inttohex(Integer(str[i]),4);
end;
result:=s;
end;
Using the linked StringToHex16 gives me this hex string:
041C04380445043004380301043B002004120430044104380301043B044C04350432043804470020041B043E043C043E043D043E03010441043E0432
I am a bit naive with this topic and I would appreciate any help you can provide to convert this hex string back to the original input.
The linked function produces four hexadecimal digits for each character in the input string, so your inverse function needs to take blocks of four characters and convert them into one. The function used
IntToHexto convert the numeric character codes of the input string into the output characters, and the inverse ofIntToHexisStrToIntwith the hex prefix, so let’s use that.This function assumes the input was generated by
StringToHex16or something equivalent. If it doesn’t consist of a multiple of four hexadecimal digits, behavior is undefined.