十六进制字符串到ASCII转换和ASCII到十六进制转换 [英] Hex string to ASCII conversion and ASCII to Hex conversion
问题描述
我写了两种方法将十六进制字符串转换为ASCII,将ASCII字符串转换为十六进制字符串。但是当我比较两个字符串时,我得到两个不同的Hex字符串。
例如:
十六进制字符串= 6220000008a01000
我使用以下方法将此字符串转换为ASCII
Hi,
I have write two methods to convert Hex string to ASCII and ASCII string to Hex string. But when I compare the two strings it I getting two difference Hex strings.
Eg:
Hex string = 6220000008a01000
I convert this string to ASCII using below method
public static string ConvertHex(string hexString)
{
try
{
string ascii = string.Empty;
for (int i = 0; i < hexString.Length; i += 2)
{
string hs = string.Empty;
hs = hexString.Substring(i, 2);
ulong decval = Convert.ToUInt64(hs, 16);
long deccc = Convert.ToInt64(hs, 16);
char character = Convert.ToChar(deccc);
ascii += character;
}
return ascii;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return string.Empty;
}
我将该ASCII值转换回十六进制字符串使用以下方法
and I convert that ASCII value back to hex string using below method
public string ASCIItoHex(string Value)
{
StringBuilder sb = new StringBuilder();
byte[] inputByte = Encoding.UTF8.GetBytes(Value);
foreach (byte b in inputByte)
{
sb.Append(string.Format("{0:x2}", b));
}
return sb.ToString();
}
但是作为最后的十六进制字符串,我得到字符串。
十六进制字符串= 6220000008c2a01000
任何人都可以帮我弄清楚那里发生的事情。
But as the final hex string I get below string.
Hex string = 6220000008c2a01000
Can anyone help me to figure it out what happen in there.
推荐答案
试试这个:
Try this:
public string ASCIItoHex(string Value)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in Value)
{
sb.Append(string.Format("{0:x2}", b));
}
return sb.ToString();
}
这篇关于十六进制字符串到ASCII转换和ASCII到十六进制转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!