C# 16进制字符串与byte[]字节数组相互转换

C# 16进制字符串与byte[]字节数组相互转换
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace ConsoleApp23
{
    class Program
    {
        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();
        }
    }
}

作者最新文章
Winform TextBox (文本框) 密码输入框, 输入内容显示*号 (星号)
Winform 启动前弹出登录界面, 登录成功之后再显示主界面
C# 字符串string和字符数组char[]的相互转换
C# 字符串倒序输出, 实现字符串倒序的方法
Winform 如何从 TextBox(文本框) 控件读取每一行数据到数组