16进制格式的string转化为byte[]

     例如将"ae00cf'转化为0xae00cf,"3031"转成new byte[]{0x30,0x31};

  public static byte[] GetBytes(string hexString, out int discarded)
        {
            discarded = 0;
            string newString = "";
            char c;
            // remove all none A-F, 0-9, characters
            for (int i=0; i<hexString.Length; i++)
            {
                c = hexString[i];
                if (IsHexDigit(c))
                    newString += c;
                else
                    discarded++;
            }
            // if odd number of characters, discard last character
            if (newString.Length % 2 != 0)
            {
                discarded++;
                newString = newString.Substring(0, newString.Length-1);
            }

            int byteLength = newString.Length / 2;
            byte[] bytes = new byte[byteLength];
            string hex;
            int j = 0;
            for (int i=0; i<bytes.Length; i++)
            {
                hex = new String(new Char[] {newString[j], newString[j+1]});
                bytes[i] = HexToByte(hex);
                j = j+2;
            }
            return bytes;
        }
调试结果运行以后出现"当前上下文中不存在HexToByte"错误,我认为出现这个错误的原因是:文中我只定义了局部变量,并未定义全局变量。
接下来再在后面定义全局变量。
 private static byte HexToByte(string hex)
        {
            byte tt = byte.Parse(hex, System.Globalization.NumberStyles.HexNumber);
            return tt;
        }

这样就可以了!

 

posted on 2015-03-06 15:04  陌上清欢  阅读(437)  评论(1)    收藏  举报

导航