I have a string 'MIROKU'
. I want to convert this string to '%82l%82h%82q%82n%82j%82t'
. Below is my current function which I have used for converting:
function MyEncode(const S: string; const CodePage: Integer): string;
var
Encoding: TEncoding;
Bytes: TBytes;
b: Byte;
sb: TStringBuilder;
begin
Encoding := TEncoding.GetEncoding(CodePage);
try
Bytes := Encoding.GetBytes(S);
finally
Encoding.Free;
end;
sb := TStringBuilder.Create;
try
for b in Bytes do begin
sb.Append('%');
sb.Append(IntToHex(b, 2));
end;
Result := sb.ToString;
finally
sb.Free;
end;
end;
MyEncode('MIROKU', 932)
returns '%82%6C%82%68%82%71%82%6E%82%6A%82%74'
. I don't expect this result. I expect '%82l%82h%82q%82n%82j%82t'
. Are there any functions to convert it correctly?
What you are seeing is correct, just not what you are expecting. %6C
, for example, is the ascii representation for l
. So you could try something like this instead:
function MyEncode(const S: string; const CodePage: Integer): string;
var
Encoding: TEncoding;
Bytes: TBytes;
b: Byte;
sb: TStringBuilder;
begin
Encoding := TEncoding.GetEncoding(CodePage);
try
Bytes := Encoding.GetBytes(S);
finally
Encoding.Free;
end;
sb := TStringBuilder.Create;
try
for b in Bytes do begin
if (b in [65..90]) or (b in [97..122]) then
begin
sb.Append( char(b)); // normal ascii
end
else
begin
sb.Append('%');
sb.Append(IntToHex(b, 2));
end;
end;
Result := sb.ToString;
finally
sb.Free;
end;
end;
Or you could leave it as is!