C# 十六进制转ascii
我正在尝试使用以下方法将十六进制字符串转换为 ASCII:
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);
}
但我收到了超出或界限异常,我确信它是一个明显的错误,但我尝试过的其他代码也不起作用。我做错了什么?
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);
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
此代码会将十六进制字符串转换为 ASCII,您可以将其复制粘贴到类中并使用它,而无需实例化
Notes
2
= 编号。用于表示 ASCII 字符的 hexString 字符。System.Convert.ToUInt32(hs, 16)
= “将 16 进制子字符串转换为无符号 32 位 int”This code will convert the hex string into ASCII, you can copy paste this into a class and use it without instancing
Notes
2
= the no. of hexString chars used to represent an ASCII character.System.Convert.ToUInt32(hs, 16)
= "convert the base 16 hex substrings to an unsigned 32 bit int"这里有
四个三个问题:由于每次迭代都会将i
增加2,因此需要在hexString.Length - 1<处终止/code>.
这实际上并不重要;无论如何,在最终迭代后增加 2 将使计数器高于检查的长度。
hexString
中获取的字符数错误。hs
从未被使用过。sb
添加任何内容。试试这个:
请注意,无需使用其命名空间
System
来限定类型(假设您已使用using
语句在文件顶部引用了它)。There are
fourthree problems here: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
.hexString
.hs
is never used.sb
.Try this:
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 ausing
statement).您是否注意到您从未使用过
hs
?并且您要一遍又一遍地转换前 2 个字符?
Do you notice you're never using
hs
??And that you're converting the first 2 chars over and over?
由于您要将索引增加 2,因此您需要在字符串长度末尾之前停止循环。否则,循环的最后一次迭代将尝试读取字符串末尾之后的字符。
Since you are incrementing your index by 2, you need to stop your loop one-before-the-end of the length of the string. Otherwise your last iteration of the loop will try to read characters past the end of the string.