C# 16进制字符串转换byte[]数组

C# 16进制字符串转换byte[]数组

static void Main(string[] args)
{
    // 16进制字符串, 0x000000000002654D
    string str = "000000000002654D";// 或者 02654D

    // 16进制字符串 -> bytes
    byte[] a = BytesToHexString(str);

    // bytes -> 16进制字符串
    string hex = BytesToHexString(a);

    // 转换数值
    long b = Convert.ToInt64(hex, 16);

    Console.Read();
}

/// <summary>
/// 16进制字符串转byte数组
/// </summary>
/// <param name="hexString">16进制字符</param>
/// <returns></returns>
public static byte[] BytesToHexString(string hexString)
{
    // 将16进制秘钥转成字节数组
    byte[] bytes = new byte[hexString.Length / 2];
    for (var x = 0; x < bytes.Length; x++)
    {
        var i = Convert.ToInt32(hexString.Substring(x * 2, 2), 16);
        bytes[x] = (byte)i;
    }
    return bytes;
}

/// <summary>
/// byte数组转16进制字符串
/// </summary>
/// <param name="bytes">byte数组</param>
/// <returns></returns>
public static string BytesToHexString(byte[] bytes)
{
    StringBuilder sb = new StringBuilder(bytes.Length * 3);
    foreach (byte b in bytes)
    {
        sb.Append(Convert.ToString(b, 16).PadLeft(2, '0'));
    }
    return sb.ToString().ToUpper();
}


作者最新文章
ASP.NET, ASP.NET Core WebApi 返回 Controller 返回 Json 类型结果
Visual Studio 调试 ASP.NET Core 无法连接 IIS Express 服务器
ASP.NET WebApi 与 ASP.NET Core WebApi 返回 HttpResponseMessage
SQL Server 中 CASE WHEN 使用
html table 设置表格背景图片,背景色