|  | 
 
| 这种低级代码本来售价 500万人民币。 可惜 白痴太多,而且都是穷鬼。
 注意 不要用 “复制代码” 这个按钮。
 
 
 [mw_shl_code=delphi,true]/// <summary>
 ///  StrToHex aka BytesToHex、Bytes2Hex、Str2Hex
 /// </summary>
 function StrToHex(Value: TBytes): string; //aka BytesToHex
 /// <summary>
 ///  HexToStr aka HexToBytes、Hex2Bytes、Hex2Str
 /// </summary>
 function HexToStr(Value: string): TBytes; //aka HexToBytes
 [/mw_shl_code]
 
 上面是函数定义。
 
 [mw_shl_code=delphi,true]
 
 function StrToHex(const Value: TBytes): string;
 var
 Length: Integer;
 OutBytes: TBytes;
 begin
 Length  := System.Length(Value) shl 1;
 SetLength(OutBytes, Length);
 System.Classes.BinToHex(Value, 0, OutBytes, 0, Length shr 1);
 Result := TEncoding.ASCII.GetString(OutBytes);
 end;
 
 function HexToStr(const Value: string): TBytes;
 var
 Length: Integer;
 InBytes: TBytes;
 begin
 InBytes := TEncoding.ASCII.GetBytes(Value);
 Length  := System.Length(InBytes) shr 1;
 SetLength(Result, Length);
 System.Classes.HexToBin(InBytes, 0, Result, 0, Length);
 end;
 
 下面是旧版本。不推荐。
 
 function StrToHex(Value: TBytes): string;
 var
 I: Integer;
 begin
 Result := '';
 for I := 0 to Length(Value) - 1 do
 Result := Result + IntToHex(Ord(Value[I]), 2);
 end;
 
 function HexToStr(Value: string): TBytes;
 var
 Len,
 I: Integer;
 begin
 Len := (Length(Value) div 2) + (Length(Value) mod 2);
 SetLength(Result, Len);
 Len := (Length(Value) div 2);
 for I := 0 to Len -1 do
 begin
 //Copy based 1
 Byte(Result[I]) := Byte(StrToInt('0x' + Copy(Value, I * 2 + 1, 2)));
 end;
 end;[/mw_shl_code]
 
 上面是具体实现。
 
 你们应该会发现 参数 或 返回值是Tbytes
 
 TBytes 和 string 可以用 TEncoding 互相转换。
 
 建议去看。
 跨平台 字符串 讨论(以及 字符串编码 讨论)
 http://www.2pascal.com/forum.php ... &tid=1654&fromuid=4
 (出处: 2Pascal-新时代的Pascal)
 
 Ansi 版本的具体转换办法(这个转换结果和 D7 一致)。
 
 Unicode or Wide 版本的具体转换办法。
 
 
 
 各位白痴,你们可以 举一反三 的 写出 UTF8 版本的转换代码吗(虽然老子已经是举二了,你们应该反六才对)?
 
 记住 网络上 大家最喜欢的还是 UTF8。
 
 
 
 也可以结合下面的帖子看看。
 
 跨平台 通用的 数据加密解密或编码解码的 设计思路
 http://www.2pascal.com/forum.php ... &tid=2975&fromuid=4
 (出处: 2Pascal-新时代的Pascal)
 
 
 
 
 最后再提供一个 大神写的版本
 [mw_shl_code=delphi,true]
 function StringToHex(const Value: string): string;
 var
 Length: Integer;
 InBytes, OutBytes: TBytes;
 begin
 InBytes := TEncoding.ANSI.GetBytes(Value);
 Length  := System.Length(InBytes) shl 1;
 SetLength(OutBytes, Length);
 System.Classes.BinToHex(InBytes, 0, OutBytes, 0, Length shr 1);
 Result := TEncoding.ANSI.GetString(OutBytes);
 end;
 
 function HexToString(const Hex: string): string;
 var
 Length: Integer;
 InBytes, OutBytes: TBytes;
 begin
 InBytes := TEncoding.ANSI.GetBytes(Hex);
 Length  := System.Length(InBytes) shr 1;
 SetLength(OutBytes, Length);
 System.Classes.HexToBin(InBytes, 0, OutBytes, 0, Length);
 Result := TEncoding.ANSI.GetString(OutBytes);
 end;
 ----------------------------------------------
 全能中间件QQ群:339616649 http://www.cnblogs.com/rtcmw
 [/mw_shl_code]
 
 稍微再修改一下。
 
 | 
 |