代码
/// <summary>
/// 数字转16进制字符串
/// </summary>
/// <param name="number"></param>
/// <param name="byteNumber"></param>
/// <returns></returns>
protected string ConvertToHexString(int number, int byteNumber)
{
byte[] byts = BitConverter.GetBytes(number);
if (!ServiceInitialize.IsBigEndian)
{
Array.Reverse(byts);
}
StringBuilder hex = new StringBuilder();
foreach (byte byt in byts)
{
hex.AppendFormat("{0:x2}", byt);
}
return hex.ToString().Substring(hex.Length - byteNumber * 2, byteNumber * 2);
}
/// <summary>
/// 十六进制字符串转byte流
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
protected byte[] HexStringToByteArray(string str)
{
byte[] buffer = new byte[str.Length / 2];
for (int i = 0; i < str.Length; i += 2)
{
buffer[i / 2] = (byte)Convert.ToByte(str.Substring(i, 2), 16);
}
return buffer;
}
/// <summary>
/// 十六进制字符串转化成整形
/// </summary>
/// <param name="startIndex"></param>
/// <param name="length"></param>
/// <returns></returns>
protected int GetIntByHexString(int startIndex, int length)
{
string val = m_ReceiveData.Substring(startIndex, length);
return Convert.ToInt32(val, 16);
}
/// <summary>
/// 字节流转数字,16进制字符串
/// </summary>
/// <param name="verifyCode"></param>
/// <returns></returns>
private UInt16 ByteArray16ToUInt(Byte[] verifyCode)
{
string result = string.Empty;
for (int i = 0; i < verifyCode.Length; ++i)
{
string strTemp = verifyCode[i].ToString("X");
if (1 == strTemp.Length)
{
strTemp = strTemp.Insert(0, "0");
}
result += strTemp;
}
return Convert.ToUInt16(result, 16);
}
/// <summary>
/// 字节流转数字,10进制字符串
/// </summary>
/// <param name="verifyCode"></param>
/// <returns></returns>
private UInt16 ByteArray10ToUInt(byte[] verifyCode)
{
return BitConverter.ToUInt16(verifyCode, 0);
}