1.使用循环获得返回结果
List<byte> rcvBuf = new List<byte>(256);
while (port.BytesToRead > 0)
{
System.Threading.Thread.Sleep(_RcvWait1);
byte[] RcvBytes = new byte[port.BytesToRead];
port.Read(RcvBytes, 0, RcvBytes.Length);
rcvBuf.AddRange(RcvBytes);//缓存有数据就拼接
if (rcvBuf.Count >= _rspLen)//达到协议指定长度就是停止
break;
}
byte[] rcvBytes = rcvBuf.ToArray();//list转数组
//rcvBytes 就是返回的数据,根据实际情况进行转换 ,即转16进制的数字,或者字符的ASCII
2.
/// <summary>
/// 字节组转16进制字符串
/// </summary>
/// <param name="bts"></param>
/// <returns></returns>
public static string Bytes2Hex(byte[] bts)
{
return Bytes2Hex(bts, 0, bts.Length);
}
public static string Bytes2Hex(byte[] bts, int offset, int length)
{
if (bts == null || bts.Length == 0 || (offset + length) > bts.Length)
return "";
string sRtn = "";
for (int i = offset; i < (offset + length); i++)
{
sRtn += bts[i].ToString("X2");
}
return sRtn;
}
/// <summary>
/// 字节集合转16进制字符串
/// </summary>
/// <param name="bts"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
/// <returns></returns>
public static string Bytes2Hex(List<byte> bts, int offset, int length)
{
if (bts == null || bts.Count == 0 || (offset + length) > bts.Count)
return "";
string sRtn = "";
for (int i = offset; i < (offset + length); i++)
{
sRtn += bts[i].ToString("X2");
}
return sRtn;
}
/// <summary>
/// 字节数组转带空格的字符串
/// </summary>
/// <param name="bts"></param>
/// <returns></returns>
public static string Bytes2HexWithSpace(byte[] bts)
{
if (bts == null || bts.Length == 0)
return "";
string sRtn = "";
for (int i = 0; i < bts.Length; i++)
{
sRtn += bts[i].ToString("X2") + " ";
}
return sRtn;
}
//字符串转字节
public static byte[] Hex2Bytes(string sHex)
{
return Hex2Bytes(sHex, false);
}
public static byte[] Hex2Bytes(string sHex, bool isExchange)
{
if (sHex == null || sHex.Length == 0)
return null;
sHex = sHex.Length % 2 == 0 ? sHex : "0" + sHex;
byte[] bRtns = new byte[sHex.Length / 2];
for (int i = 0; i < bRtns.Length; i++)
{
if (isExchange)
bRtns[bRtns.Length - 1 - i] = Convert.ToByte(sHex.Substring(i * 2, 2), 16);
else
bRtns[i] = Convert.ToByte(sHex.Substring(i * 2, 2), 16);
}
return bRtns;
}
public static byte[] Hex2BytesWithSpace(string sHex)
{
string[] hexs = sHex.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
byte[] bts = new byte[hexs.Length];
for (int i = 0; i < hexs.Length; i++)
{
byte bt = 0x00;
//if (!byte.TryParse(hexs[0], System.Globalization.NumberStyles.AllowHexSpecifier, null, out bt))
// return null;
byte.TryParse(hexs[i], System.Globalization.NumberStyles.AllowHexSpecifier, null, out bt);
bts[i] = bt;
}
return bts;
}