C# BYTE[] 與16進位制字串互相轉換
阿新 • • 發佈:2021-08-29
https://www.cnblogs.com/mingjing/p/14473568.html
byte[] 轉16進位制字串
方法一、
byte[] resultArray = new byte[]{1,2,3,4,5,6,7,8,9};
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; }