首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#十六进制转解决方案

2013-09-05 
C#十六进制转string text ScreenBox.TextScreenBox.Clear()byte[] textToByte Encoding.Default.Get

C#十六进制转


             string text = ScreenBox.Text;
             ScreenBox.Clear();
             byte[] textToByte = Encoding.Default.GetBytes(text);
             for (int i = 0; i < textToByte.Length; i++)
                {
                    byte temp = textToByte[i];
                    string tempHex = temp.ToString("X2") + " ";
                    ScreenBox.Text += tempHex;
                }

上面的代码是将ScreenBox控件中的文本转换为十六进制并输出在ScreenBox上;然后我再将新的文本拷贝下来。

             string Hextext = ScreenBox.Text;

最后我想将Hextext字符串转换为原先的text字符串并输出,怎么写代码?谢谢。 string c# 十六进制转换
[解决办法]
///<summary>
        /// 从16进制转换成汉字
        /// </summary>
        /// <param name="hex"></param>
        /// <param name="charset">编码,如"utf-8","gb2312"</param>
        /// <returns></returns>
        public static string UnHex(string hex, string charset)
        {
            if (hex == null)


                throw new ArgumentNullException("hex");
            hex = hex.Replace(",", "");
            hex = hex.Replace("\n", "");
            hex = hex.Replace("\", "");
            hex = hex.Replace(" ", "");
            if (hex.Length % 2 != 0)
            {
                hex += "20";//空格
            }
            // 需要将 hex 转换成 byte 数组。 
            byte[] bytes = new byte[hex.Length / 2];

            for (int i = 0; i < bytes.Length; i++)
            {
                try
                {
                    // 每两个字符是一个 byte。 
                    bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
                    System.Globalization.NumberStyles.HexNumber);
                }
                catch
                {
                    // Rethrow an exception with custom message. 
                    throw new ArgumentException("hex is not a valid hex number!", "hex");


                }
            }
            System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
            return chs.GetString(bytes);
        }


[解决办法]
取每两个16进制字符,然后convert成int,然后写入byte,在encoding编码为字符
[解决办法]

string Hextext = ScreenBox.Text;
var hexItems=Hextext.Split(' ').Where(s=>s!="").Select(s => (byte)Convert.ToInt32(s,16)).ToArray();
string value=Encoding.Default.GetString(hexItems);

热点排行