C#十六进制ASCII码 [英] C# hex to ascii
本文介绍了C#十六进制ASCII码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将字符串转换十六进制的ASCII码,使用此:
I'm trying to convert a String of hex to ASCII, using this:
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();
MessageBox.Show(ascii);
}
但我得到out或越界异常,我敢肯定它的一个明显错误,但我曾尝试其他代码也不起作用。什么?我做错了。
but I get an out or bounds exception, I'm sure its a glaring error but other code I have tried does not work either. What am I doing wrong?
推荐答案
有四线这里三个问题:
-
既然你递增这实际上并不此事。最终的迭代后由两个递增将带来检查长度以上的柜台不管。I
2在每次迭代,你需要终止hexString.Length - 1
- 您会采取错误的字符数从
十六进制串
。 -
HS
从未使用过。 - 您不是追加什么
SB
Since you're incrementingThis doesn't actually matter; incrementing by two after the final iteration will bring the counter above the checked length regardless.i
by 2 on each iteration, you need to terminate athexString.Length - 1
.- You're taking the wrong number of characters from
hexString
. hs
is never used.- You're not appending anything to
sb
.
试试这个:
for (int i = 0; i < hexString.Length; i += 2)
{
string hs = hexString.Substring(i, 2);
sb.Append(Convert.ToChar(Convert.ToUInt32(hs, 16)));
}
请注意,有没有必要用自己的命名空间来限定的类型,系统
(假设你已经在使用使用
语句的文件的顶部引用它)。
Note that there's no need to qualify the types with their namespace, System
(assuming you've referenced it at the top of the file with a using
statement).
这篇关于C#十六进制ASCII码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文