using System; using System.Text; namespace EC.Utils.Helper { public class ByteHelper { public static string IntToHex(int i) { return Convert.ToString(i, 16); } /// /// int 类型转回为 byte[] /// /// /// public static byte[] IntToByte2(int i) { byte[] a = new byte[2]; a[0] = (byte)(i >> 8); a[1] = (byte)i; return a; } /// /// 截取byte 数组 /// /// /// /// /// public static byte[] SubArr(byte[] frombyte, int begIndex, int lenth) { byte[] subByte = new byte[lenth]; int icount = (begIndex + lenth); for (int x = begIndex; x < icount; x++) { subByte[x - begIndex] = frombyte[x]; } return subByte; } public static string SubToString(byte[] frombyte, int begIndex, int lenth) { byte[] subByte = new byte[lenth]; int icount = (begIndex + lenth); for (int x = begIndex; x < icount; x++) { subByte[x - begIndex] = frombyte[x]; } return Encoding.UTF8.GetString(subByte); } /// /// 数组相加 /// /// /// /// public static byte[] Add(byte[] bytes1, byte[] bytes2) { int len1 = bytes1.Length; int len2 = bytes2.Length; int allLen = len1 + len2; byte[] newByte = new byte[allLen]; for (int x = 0; x < len1; x++) { newByte[x] = bytes1[x]; } for (int x = 0; x < len2; x++) { newByte[x + len1] = bytes2[x]; } return newByte; } /// /// subbyte 合并到 bytesA /// /// 原始数组 /// 添加数组 /// 添加起开始位置 /// public static byte[] Append(byte[] bytesA, byte[] subbytes, int index) { int len1 = subbytes.Length; for (int x = 0; x < len1; x++) { bytesA[x + index] = subbytes[x]; } return bytesA; } public static byte[] Append(byte[] bytesA, string substr, int index) { int len1 = substr.Length; byte[] subbytes = Encoding.UTF8.GetBytes(substr); for (int x = 0; x < len1; x++) { bytesA[x + index] = subbytes[x]; } return bytesA; } public static byte[] HexStringToByteArray(string s) { s = s.Replace(" ", ""); byte[] buffer = new byte[s.Length / 2]; for (int i = 0; i < s.Length; i += 2) { buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16); } return buffer; } /// Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2) /// The array of bytes to be translated into a string of hex digits. /// Returns a well formatted string of hex digits with spacing. public static string ByteArrayToHexString(byte[] data) { StringBuilder sb = new StringBuilder(data.Length * 3); foreach (byte b in data) { sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' ')); } return sb.ToString().ToUpper(); } } }