我想将十六进制转换为ASCII [英] I Want Convert Hex to Ascii
问题描述
我想将十六进制转换为ASCII.
I want convert hex to ascii.
我尝试了两种不同的方法.但是我不能成功.
I was try different two methods. But I could not be successful.
方法1:
public void ConvertHex(String hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = hexString.Substring(i, i + 2);
System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0, 2), 16)).ToString();
}
String ascii = sb.ToString();
StreamWriter wrt = new StreamWriter("D:\\denemeASCII.txt");
wrt.Write(ascii);
}
方法2:
public string HEX2ASCII(string hex)
{
string res = String.Empty;
for (int a = 0; a < hex.Length; a = a + 2)
{
string Char2Convert = hex.Substring(a, 2);
int n = Convert.ToInt32(Char2Convert, 16);
char c = (char)n;
res += c.ToString();
}
return res;
}
传入错误消息:(
我该怎么办?
推荐答案
您的"Method1"有几率被重写为可以正常工作.(您的"Method2"绝望了.)
Your "Method1" has a few chances of being rewritten to work. (Your "Method2" is hopeless.)
因此,在"Method1"中,您执行 String hs = hexString.Substring(i,i + 2)
,然后您忘记了 hs
曾经存在过.(编译器是否应该对此发出警告?)然后继续执行 System.Convert.ToChar(System.Convert.ToUInt32(hexString.Substring(0,2),16))
,但 hexString.Substring(0,2)
将始终选择 hexString
的前两个字符,而不是 i
所指向的两个字符.相反,您可能想做的是: System.Convert.ToChar(System.Convert.ToUInt32(hs,16))
So, in "Method1", you do String hs = hexString.Substring( i, i + 2 )
and then you forget that hs
ever existed. (Shouldn't the compiler be giving you a warning about that?) Then you proceed to do System.Convert.ToChar( System.Convert.ToUInt32( hexString.Substring( 0, 2 ), 16 ) )
but hexString.Substring( 0, 2 )
will always pick the first two characters of the hexString
, not the two characters pointed by i
. What you probably meant to do is this instead: System.Convert.ToChar( System.Convert.ToUInt32( hs , 16) )
此外,您正在声明 StringBuilder sb;
,但从未添加任何内容.同时, System.Convert.ToChar()
无效.它返回一个值;如果您对返回值不做任何事情,则返回值将永远丢失.您可能要做的就是将 System.Convert.ToChar()
的结果添加到您的 StringBuilder
中.
Also, you are declaring a StringBuilder sb;
but you are never adding anything to it. At the same time, System.Convert.ToChar()
does not work by side effect; it returns a value; if you don't do anything with the returned value, the returned value is lost forever. What you probably meant to do is add the result of System.Convert.ToChar()
to your StringBuilder
.
这篇关于我想将十六进制转换为ASCII的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!