2014-02-21 1 views
0

16 진수 값을 10 진수 값으로 변환하는 수신기 소프트웨어를 만들려고합니다. 이건 내 코드입니다 :HexString에서 Decimal로 변환 오류 : 인덱스가 범위를 벗어났습니다. 음수가 아니어야하며 콜렉션의 크기보다 작아야합니다. 매개 변수 이름 : 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"); 
     } 

하지만 그것은 항상 인덱스가 범위를 벗어났습니다 "라고 시리얼 데이터를 보내려고 할 때 컬렉션의 크기보다 음이 아닌 및 작아야합니다 매개 변수 이름 :.. 시작 인덱스 ". 그래서 내가 뭘하는거야?

+0

어떤 라인에서 오류가 발생합니까? –

+0

나는 당신이 제공하지 않은'ByteArrayToHexString'에 있다고 생각합니다 : ( –

답변

2

문제 :

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

hex 값이 같은 경우 문자열이 비어 있으면 사항 String.split() 함수를 사용하는 동안 다음 반환 빈 문자열, 내가이 문을 의심

는 예외가 발생합니다 빈 상태이면 원인 : Index was out of range. Must be non-negative Exception.

해결책 1 : 당신은 providin g StringSplitOptions.RemoveEmptyEntriesSplit() 함수의 두 번째 인수로 사용됩니다.

이 시도 :

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

또는

해결 방법 2 : 당신은 단순히 Null 또는 EmptyString.IsNullOrEmpty() 방법을 사용하기위한 hex 변수를 확인할 수 있습니다.

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' 값이 비어 있으면'Index is out of range. 부정적이 아닌 예외 여야합니다. –

+1

여기에 'startIndex' 매개 변수가 없다는 것을 감안할 때 매우 실망스러운 구현입니다. –

관련 문제