Delphi: Convert from windows-1251 to Shift-JIS

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-07 04:59:06

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/42550568/delphi-convert-from-windows-1251-to-shift-jis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!