C# 16進位制(hex)字串到位元組流的轉換 示例
阿新 • • 發佈:2019-02-10
在工程實踐中,經常會將一些位元組資訊轉換為16進位制字串,以便傳遞和分享,比如加密金鑰資訊。在這裡提供一段轉化示例, 以供交流學習。
將16進位制字串轉化為 位元組流
public static byte[] HexStringToBytes(string hexStr) { if (string.IsNullOrEmpty(hexStr)) { return new byte[0]; } if (hexStr.StartsWith("0x")) { hexStr = hexStr.Remove(0, 2); } var count = hexStr.Length; if (count % 2 == 1) { throw new ArgumentException("Invalid length of bytes:" + count); } var byteCount = count / 2; var result = new byte[byteCount]; for (int ii = 0; ii < byteCount; ++ii) { var tempBytes = Byte.Parse(hexStr.Substring(2 * ii, 2), System.Globalization.NumberStyles.HexNumber); result[ii] = tempBytes; } return result; }
將位元組流轉化為16進位制字串
public static string BytesTohexString(byte[] bytes) { if (bytes == null || bytes.Count() < 1) { return string.Empty; } var count = bytes.Count(); var cache = new StringBuilder(); cache.Append("0x"); for (int ii = 0; ii < count; ++ii) { var tempHex = Convert.ToString(bytes[ii], 16).ToUpper(); cache.Append(tempHex.Length == 1 ? "0" + tempHex : tempHex); } return cache.ToString(); }