C#十六进制ASCII码 [英] C# hex to ascii

查看:156
本文介绍了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?

推荐答案

四线这里三个问题:


  1. 既然你递增 I 2在每次迭代,你需要终止 hexString.Length - 1 这实际上并不此事。最终的迭代后由两个递增将带来检查长度以上的柜台不管。

  2. 您会采取错误的字符数从十六进制串

  3. HS 从未使用过。

  4. 您不是追加什么 SB

  1. Since you're incrementing i by 2 on each iteration, you need to terminate at hexString.Length - 1. This doesn't actually matter; incrementing by two after the final iteration will bring the counter above the checked length regardless.
  2. You're taking the wrong number of characters from hexString.
  3. hs is never used.
  4. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆