[英]HexString to Decimal Convert Error : Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: startIndex
I try to make a receiver software which convert hexadecimal value from serial to decimal value. 我尝试制作一个接收器软件,将十六进制值从串行转换为十进制值。 This is my code :
这是我的代码:
// Obtain the number of bytes waiting in the port's buffer
int bytes = comport.BytesToRead;
// Create a byte array buffer to hold the incoming data
byte[] buffer = new byte[bytes];
// Read the data from the port and store it in our buffer
comport.Read(buffer, 0, bytes);
string hexValues = ByteArrayToHexString(buffer);
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String hex in hexValuesSplit)
{
// Convert the number expressed in base-16 to an integer.
int value = Convert.ToInt32(hex, 16);
Log(LogMsgType.Incoming, value+" ppm \n");
}
But when I try to send data from serial it always say that "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: startIndex". 但是当我尝试从串行发送数据时,它总是说“索引超出范围。必须是非负的且小于集合的大小。参数名称:startIndex”。 So What shoul I do?
那我该怎么办?
Problem : while using String.Split() function if the string is EMPTY then it returns EMPTY string, 问题:当使用String.Split()函数时,如果字符串是EMPTY,那么它返回EMPTY字符串,
I suspect this statement causes the Exception: 我怀疑这个语句会导致异常:
int value = Convert.ToInt32(hex, 16);
if the hex
value is Empty then it causes the Index was out of range. Must be non-negative Exception.
如果
hex
值为Empty,则会导致Index was out of range. Must be non-negative Exception.
Index was out of range. Must be non-negative Exception.
Solution 1: You need to Remove the empty entries by providing StringSplitOptions.RemoveEmptyEntries
as second argument to the Split()
function. 解决方案1:您需要通过提供
StringSplitOptions.RemoveEmptyEntries
作为Split()
函数的第二个参数来删除空条目。
Try This: 尝试这个:
string[] hexValuesSplit = hexValues.Split(new []{' '},StringSplitOptions.RemoveEmptyEntries);
OR 要么
Solution 2 : You can simply check the hex
variable for Null
or Empty
using String.IsNullOrEmpty()
method. 解决方案2:您可以使用
String.IsNullOrEmpty()
方法简单地检查hex
变量的Null
或Empty
。
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String hex in hexValuesSplit)
{
if(!String.IsNullOrEmpty(hex))
{
// Convert the number expressed in base-16 to an integer.
int value = Convert.ToInt32(hex, 16);
Log(LogMsgType.Incoming, value+" ppm \n");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.