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();
}
}
}