C# int 转 16进制的字符串 in to hex string


网上有人写的,其中有个错误,只需把大于号改成大于等于就好了,在此重新发一下。在framework 2.0里面bitconverter不够强大。所以不得不自己写个函数

以前是

while (ulong.Parse(value) > 16)

我将其改成了 

while (ulong.Parse(value) >= 16)

测试了很多数据,结果是一致的。

 

public class CryptString
    {
        ///  
        /// 转换数字成单个16进制字符,要求输入值小于16
        ///  
        /// value
        ///  
        public static string GetHexChar(string value)
        {
            string sReturn = string.Empty;
            switch (value)
            {
                case "10":
                    sReturn = "A";
                    break;
                case "11":
                    sReturn = "B";
                    break;
                case "12":
                    sReturn = "C";
                    break;
                case "13":
                    sReturn = "D";
                    break;
                case "14":
                    sReturn = "E";
                    break;
                case "15":
                    sReturn = "F";
                    break;
                default:
                    sReturn = value;
                    break;
            }
            return sReturn;
        }

        ///  
        /// 返回进制字符串
        ///  
        /// value
        ///  

        public static string ConvertHex(string value)
        {
            string sReturn = string.Empty;
            try
            {

                while (ulong.Parse(value) >= 16)
                {
                    ulong v = ulong.Parse(value);
                    sReturn = GetHexChar((v % 16).ToString()) + sReturn;
                    value = Math.Floor(Convert.ToDouble(v / 16)).ToString();
                }
                sReturn = GetHexChar(value) + sReturn;
            }
            catch
            {
                sReturn = "###Valid Value!###";
            }
            return sReturn;
        }
    } 


 

 

 

 

 

 

 

你可能感兴趣的:(c,String,C#,测试,Class,hex)