//1、 將字節數組轉化為數值

public static int ConvertBytesToInt(byte[] arrByte, int offset)


...{

return BitConverter.ToInt32(arrByte, offset);

}


//2、 將數值轉化為字節數組

//第二個參數設置是不是需要把得到的字節數組反轉,因為Windows操作系統中整形的高低位是反轉轉之後保存的。

public static byte[] ConvertIntToBytes(int value, bool reverse)


...{

byte[] ret = BitConverter.GetBytes(value);

if (reverse)

Array.Reverse(ret);

return ret;

}


//3、 將字節數組轉化為16進制字符串

//第二個參數的含義同上。

public static string ConvertBytesToHex(byte[] arrByte, bool reverse)


...{

StringBuilder sb = new StringBuilder();

if (reverse)

Array.Reverse(arrByte);

foreach (byte b in arrByte)

sb.AppendFormat("{0:x2}", b);

return sb.ToString();



//4、 將16進制字符串轉化為字節數組

public static byte[] ConvertHexToBytes(string value)


...{

int len = value.Length / 2;

byte[] ret = new byte[len];

for (int i = 0; i < len; i++)

ret[i]=(byte)(Convert.ToInt32(value.Substring(i * 2, 2), 16));

return ret;

}
