编程语言
首页 > 编程语言> > C# byte[] 与16进制字符串互相转换

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

作者:互联网

byte[] 转16进制字符串

方法一、

BitConverter.ToString(resultArray).Replace("-", "")

方法二、

/// <summary> 
/// 字节数组转16进制字符串 
/// </summary> 
/// <param name="bytes"></param> 
/// <returns></returns> 
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;
}

16进制的字符串转为byte[]

/// <summary>
/// 将16进制的字符串转为byte[]
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] StrToHexByte(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), 16);
	return returnBytes;
}

标签:进制,16,C#,hexString,bytes,Length,byte
来源: https://blog.csdn.net/BeanGo/article/details/119443295