1、int整形转为byte[]数组:高位存储在前,低位存储在后
public static byte[] IntToByte(this int source, int fromebase = 4)
{List<byte> buff = new List<byte>();for (int i = fromebase - 1; i >= 0; i--){buff.Add((byte)(source>>(8 * i)));}return buff.ToArray();
}
2、字符串转对应ASCII码,byte[]数组
public static byte[] StringToByte(this string source){return Encoding.Default.GetBytes(source);}
3、十六进制字符串数组转为byte[]数组
public static byte[] HexStringToByte(this string source){if (string.IsNullOrEmpty(source))return new byte[0];List<byte> buff = new List<byte>();for (int i = 0; i < source.Length; i += 2){buff.Add(Convert.ToByte(source.Substring(i, 2), 16));}return buff.ToArray();}
4、获取byte[]指定的区域的数组,offset:首地址;count:个数
public static byte[] GetBytes(this byte[] source, int offset, int count){byte[] buff = new byte[count];int total = offset + count;int index = 0;for (int i = offset; i < total; i++){buff[index] = source[i];index++;}return buff;}
5、byte转为十六进制字符串 并补位
public static string ToHexString(this byte b){return b.ToString("X2");}
6、指定byte[]区域内 转十六进制字符串
public static string ToHexString(this byte[] datas, int offset, int count){StringBuilder str = new StringBuilder();int total = offset + count;for (int i = offset; i < total; i++){str.Append(datas[i].ToString("X2"));}return str.ToString();}
7、byte转int字符串
public static string ToIntString(this byte b){return b.ToString("D");}
8、byte[]转int字符串
public static string ToIntString(this byte[] datas, int offset, int count){StringBuilder str = new StringBuilder();int total = offset + count;for (int i = offset; i < total; i++){str.Append(datas[i].ToString("D"));}return str.ToString();}
9、byte[]转int字符串,split:分割字符串
public static string ToIntString(this byte[] datas, int offset, int count, string split = ""){StringBuilder str = new StringBuilder();int total = offset + count;for (int i = offset; i < total; i++){if (i > offset){str.Append(split);}str.Append(datas[i].ToString("D"));}return str.ToString();}
10、整形转byte[]数组:BitConverter.GetBytes,低位在前,高位在后;以字节数组的形式返回指定的 32 位有符号整数值。返回为4的字节数组
int iResult = 20000;
byte[] array = BitConverter.GetBytes(iResult);
11、byte[]数组转整形:BitConverter.ToInt32,低位在前,高位在后
byte[] array = new byte[4]{0x01,0x02,0x03,0x04};
BitConverter.ToInt32(datas,array);
**************************************************************************************************************