欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

字符串和十六进制之间的转换方法实例

程序员文章站 2024-02-21 15:36:22
复制代码 代码如下:///         /// <函数:enc...

复制代码 代码如下:

/// <summary>
        /// <函数:encode>
        /// 作用:将字符串内容转化为16进制数据编码,其逆过程是decode
        /// 参数说明:
        /// strencode 需要转化的原始字符串
        /// 转换的过程是直接把字符转换成unicode字符,比如数字"3"-->0033,汉字"我"-->u+6211
        /// 函数decode的过程是encode的逆过程.
        /// </summary>
        /// <param name="strencode"></param>
        /// <returns></returns>
        public static string encode(string strencode)
        {
            string strreturn = "";//  存储转换后的编码
            foreach (short shortx in strencode.tochararray())
            {
                strreturn += shortx.tostring("x4");
            }
            return strreturn;
        }
        /// <summary>
        /// <函数:decode>
        ///作用:将16进制数据编码转化为字符串,是encode的逆过程
        /// </summary>
        /// <param name="strdecode"></param>
        /// <returns></returns>
        public static string decode(string strdecode)
        {
            string sresult = "";
            for (int i = 0; i < strdecode.length / 4; i++)
            {
                sresult += (char)short.parse(strdecode.substring(i * 4, 4), global::system.globalization.numberstyles.hexnumber);
            }
            return sresult;
        }