字符串转化成十六进制输出StrToHex(Delphi版、C#版)
//注意:Delphi2010以下版本默认的字符编码是ANSI,VS2010的默认编码是UTF-8,delphi版字符串事先须经过AnsiToUtf8()转码才能跟C#版得到的十六进制字符串显示结果一致。
Delphi版:
function StrToHex(AStr: string): string;
var
i : Integer;
ch:char;
begin
Result:='';
for i:=1 to length(AStr) do
begin
ch:=AStr[i];
Result:=Result+IntToHex(Ord(ch),2);
end;
end;
复制代码
//***************************************************
C#版
public string StrToHex(string str)
{
string strResult;
byte[] buffer = Encoding.GetEncoding("utf-8").GetBytes(str);
strResult = "";
foreach (byte b in buffer)
{
strResult += b.ToString("X2");//X是16进制大写格式
}
return strResult;
}
Delphi 十六进制字符串转化成字符串输出HexToStr(Delphi版、C#版)
//注意: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#版:
///
/// 从16进制转换成汉字
///
///
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);
}
来源:https://www.cnblogs.com/mumble/p/3757600.html