Delphi:从 windows-1251 转换为 Shift-JIS
Delphi: Convert from windows-1251 to Shift-JIS
我有一个字符串 'MIROKU'
。我想将此字符串转换为 '%82l%82h%82q%82n%82j%82t'
。以下是我用于转换的当前函数:
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'
。我不期待这个结果。我预计 '%82l%82h%82q%82n%82j%82t'
。有什么函数可以正确转换吗?
您看到的是正确的,只是不是您所期望的。例如,%6C
是 l
的 ascii 表示。所以你可以尝试这样的事情:
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;
或者您可以保持原样!
我有一个字符串 'MIROKU'
。我想将此字符串转换为 '%82l%82h%82q%82n%82j%82t'
。以下是我用于转换的当前函数:
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'
。我不期待这个结果。我预计 '%82l%82h%82q%82n%82j%82t'
。有什么函数可以正确转换吗?
您看到的是正确的,只是不是您所期望的。例如,%6C
是 l
的 ascii 表示。所以你可以尝试这样的事情:
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;
或者您可以保持原样!