C#16进制转换

发布时间:2020-10-15 16:19:28来源:本站阅读(842)

    1、数字转16进制

    var a=1;
    var b=Convert.ToString(a,16);

    2、字符转16进制

    private static string StringToHexString(string s, Encoding encode)
    {
    byte[] b = encode.GetBytes(s);//按照指定编码将string编程字节数组
    string result = string.Empty;
    for (int i = 0; i < b.Length; i++)
    {
    result += Convert.ToString(b[i], 16);
    }
    return result;
    }

    3、byte[]转16进制

    public static string ByteToHexStr(byte[] bytes)
    {
    string returnStr = "";
    if (bytes != null)
    {
    for (int i = 0; i < bytes.length; i++)
    {
    returnStr += bytes[i].ToString("X2");
    }
    }
    return returnStr;
    }

    4、16进制转byte[]

    private static byte[] StrToByte(string hexString)
    {
    hexString = hexString.Replace(" ", "");
    if ((hexString.Length % 2) != 0)
    hexString += " ";

    byte[] returnBytes = new byte[hexString.Length / 2];
    for (int i = 0; i < returnBytes.Length; i++)
    {
    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
    }
    return returnBytes;

    }


关键字