您的位置:首页 > 编程语言 > Delphi

十六进制字符串转化成字符串输出HexToStr(Delphi版、C#版)

2016-04-07 15:15 585 查看

//注意:Delphi2010以下版本默认的字符编码是ANSI,VS2010的默认编码是UTF-8,delphi版得到的字符串须经过Utf8ToAnsi()转码才能跟C#版得到的字符串显示结果一致。

//Delphi版:

function HexToStr(str: string): string;
function HexToInt(hex: string): integer;
var
i: integer;
function Ncf(num, f: integer): integer;
var
i: integer;
begin
Result := 1;
if f = 0 then exit;
for i := 1 to f do
result := result * num;
end;
function HexCharToInt(HexToken: char): integer;
begin
if HexToken > #97 then
HexToken := Chr(Ord(HexToken) - 32);
Result := 0;
if (HexToken > #47) and (HexToken < #58) then { chars 0....9 }
Result := Ord(HexToken) - 48
else if (HexToken > #64) and (HexToken < #71) then { chars A....F }
Result := Ord(HexToken) - 65 + 10;
end;
begin
result := 0;
hex := ansiuppercase(trim(hex));
if hex = '' then
exit;
for i := 1 to length(hex) do
result := result + HexCharToInt(hex[i]) * ncf(16, length(hex) - i);
end;
var
s, t: string;
i, j: integer;
p: pchar;
begin
s := '';
i := 1;
while i < length(str) do begin
t := str[i] + str[i + 1];
s := s + chr(hextoint(t));
i := i + 2;
end;
result := s;
end;


//********************************************************************

C#版:

///<summary>
/// 从16进制转换成汉字
/// </summary>
/// <param name="hex"></param>
/// <param name="charset">编码,如"utf-8","gb2312"</param>
/// <returns></returns>
public  string HexToStr(string hex, string charset)
{
if (hex == null)
throw new ArgumentNullException("hex");
hex = hex.Replace(",", "");
hex = hex.Replace("\n", "");
hex = hex.Replace("\\", "");
hex = hex.Replace(" ", "");
if (hex.Length % 2 != 0)
{
hex += "20";//空格
}
// 需要将 hex 转换成 byte 数组。
byte[] bytes = new byte[hex.Length / 2];

for (int i = 0; i < bytes.Length; i++)
{
try
{
// 每两个字符是一个 byte。
bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
System.Globalization.NumberStyles.HexNumber);
}
catch
{
// Rethrow an exception with custom message.
throw new ArgumentException("hex is not a valid hex number!", "hex");
}
}
System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
return chs.GetString(bytes);
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: