{****16进制单字符值*****} function HexVal(c: char): Byte; begin if (c<'A') then result := ord(c) - ord('0') else result := ord(c) - ord('A') + 10; end; {****16进制双字符值*****} function Hex2Val(s: string): Byte; begin result := HexVal(s.Chars[0])*16 + HexVal(s.Chars[1]); end; {**********字符串转换成字节*******} function StrToBytes(S, AFormat: string): TBytes; var i:Integer; ss:TStrings; begin if(AFormat='Str') then begin SetLength(result,s.Length); for i:=0 to s.Length-1 do result[i]:=ord(s.Chars[i]); end else begin ss:=TStringList.Create; ss.CommaText:=s.Trim.ToUpper.Replace(' ',','); SetLength(result,ss.Count); if(AFormat='HexStr') then for i:=0 to ss.Count-1 do result[i]:=Hex2Val(ss[i]); if(AFormat='DecStr') then for i:=0 to ss.Count-1 do result[i]:=ss[i].ToInteger; ss.Free; end end; {**********字节转换成字符串*******} function BytesToStr(b: TBytes; AFormat: string): string; var I: Byte; begin result := ''; if (AFormat = 'str') then for i in b do result := result + chr(I) else if (AFormat = 'HexStr') then for I in b do result := result + I.ToHexString(2) + '' else if (AFormat = 'DecStr') then for i in b do result := result + I.ToString() + ''; result := result.Trim; end;
function Do_Decode(const S_Unicode: UnicodeString): UTF8String; var aBytes: TBytes; i, aLength: Integer; begin aLength := Length(S_Unicode); SetLength(aBytes, aLength); for i := 1 to aLength do aBytes[i - 1] := Word(S_Unicode[i]); Result := TEncoding.UTF8.GetString(aBytes); end; function Do_Encode(const S_UTF8: UTF8String): UnicodeString; var aBytes: TBytes; i, aLength: Integer; begin aBytes := TEncoding.UTF8.GetBytes(S_UTF8); aLength := Length(aBytes); SetLength(Result, aLength); for i := 1 to aLength do Result[i] := Char(Word(aBytes[i - 1])); end;
楼上的代码很好。就是有点不跨平台。 str := 'hello你好.txt'; aBytes := TEncoding.UTF8.GetBytes(str); str := ''; for I := 0 to Length(ABytes) - 1 do begin str := str + Chr(ABytes[I] ); end; //以上是生成错误编码的字符串。 SetLength(aBytes, Length(str)); for I := 0 to Length(ABytes) - 1 do begin ABytes[I] := Byte(str[Low(str) + I]); end; str := TEncoding.UTF8.GetString(ABytes);