2014-02-21 20 views
0

我尝试制作一个将十六进制值从串行转换为十进制值的接收器软件。这是我的代码:十六进制到十进制转换错误:索引超出范围。必须是非负数且小于集合的大小。参数名称:startIndex

 // 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"); 
     } 

但是,当我尝试发送从串行它总是说,“索引超出范围的数据必须为非负数且小于集合的大小参数名:的startIndex ”。那么我该怎么做?

+0

哪条线会抛出错误? –

+0

我怀疑它在'ByteArrayToHexString'中,你没有提供:( –

回答

2

问题:在使用String.Split()函数,如果字符串为空,则返回空字符串,

我怀疑这种说法引起了异常:

int value = Convert.ToInt32(hex, 16); 

如果hex值是空的,那么它会导致Index was out of range. Must be non-negative Exception.

解决方案1:您需要删除通过提供的空条目g StringSplitOptions.RemoveEmptyEntries作为Split()函数的第二个参数。

试试这个:

string[] hexValuesSplit = hexValues.Split(new []{' '},StringSplitOptions.RemoveEmptyEntries); 

OR

解决方案2:你可以简单地检查hex变量NullEmpty使用String.IsNullOrEmpty()方法。

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"); 
} 
} 
+0

这不会给出有问题的错误 –

+0

@JonSkeet:如果'hex'值是EMPTY,它会抛出索引超出范围。必须是非负面的例外 –

+1

你说得对,它确实 - 这是一个非常糟糕的实现,因为*有*没有'startIndex'参数 –

相关问题