比如将 hello 转成 \x68\x65\x6c\x6c\x6f如能带扩展性更好,比如还能转成 \u0068\u0065\u006c\u006c\u006f , 或者 hello等

解决方案 »

  1.   

    string test = "hello";
    string[] denotion = new string[test.Length];
    for (int i = 0; i < test.Length;i++ ) 
    {
        // \x68\x65\x6c\x6c\x6f
        denotion[i] = String.Format(@"\x{0}", ((Int32)test[i]).ToString("x2"));    // \u0068\u0065\u006c\u006c\u006f
        //denotion[i] = String.Format(@"\u{0}", ((Int32)test[i]).ToString("x4"));
        
        // &#x0068;&#x0065;&#x006c;&#x006c;&#x006f;
        //denotion[i] = String.Format(@"&#x{0};", ((Int32)test[i]).ToString("x4"));
    }MessageBox.Show(String.Join("", denotion));
      

  2.   

        //数组转化为16进制字符串 重载 截取长度
                public static string ByteArrayToHexString(byte[] data, int len)
                {
                    byte[] datatemp = new byte[len];
                    for (int i = 0; i < len; i++)
                    {
                        datatemp[i] = data[i];
                    }                StringBuilder sb = new StringBuilder(datatemp.Length * 3);
                    foreach (byte b in datatemp)
                        sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
                    return sb.ToString().ToUpper();
                }
      

  3.   

        //数组转化为16进制字符串 重载 截取长度
                public static string ByteArrayToHexString(byte[] data, int len)
                {
                    byte[] datatemp = new byte[len];
                    for (int i = 0; i < len; i++)
                    {
                        datatemp[i] = data[i];
                    }                StringBuilder sb = new StringBuilder(datatemp.Length * 3);
                    foreach (byte b in datatemp)
                        sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
                    return sb.ToString().ToUpper();
                }