2013-03-18 5 views
0

데이터가 있습니다 string data2 = " %04%02%BC%94%BA%15%E3%AA%08%00%7F%00";% 기호 사이에 두 자리를 나누어 배열에 넣으려고합니다.문자열 조작 및 분할

그 외에도 2 자리 이상의 추가 숫자가있는 경우 16 진수로 변환하여 배열에 추가하십시오.

때때로 코드가 작동하지만 두 번째 마지막 자리에 추가 숫자를 추가하면 잘못된 값이 표시됩니다. 추가 번호가 제 1 위치에 추가

string data = " %04F%02%BC%94%BA%15%E3%AA%08%00%7FF%00"; 

     List<string> Values = new List<string>(); 

     string[] val = Regex.Split(data2, "%"); 
     byte[] TempByte = new byte[val.Length - 1]; 


     for (int i = 0; i < val.Length; i++) 
     { 
      Values.Add(val[i]); 

      if (Values[i].Length > 2) 
      { 
       //count 
       int count = 0; 
       int n = 2;      //start from digit 2(if ther is any) 
       foreach (char s in Values[i]) 
       { 
        count++; 
       } 
       int index = count - 2;   //index starting at 2 

       while (n <= Values[i].Length -1)  
       { 
        string temp = string.Join(string.Empty, Values[i].Substring(n, 1).Select(c => 
                 ((int)c).ToString("X")).ToArray()); 


        Values.Add(temp); 
        n = n + 1; 
       } 
       //remove the extra digit 
       Values[i] = Values[i].Replace(Values[i].Substring(2, 1), string.Empty); 

      } 
     } 


     Values.RemoveAt(0);      //since digit 0 is always zero 
     string[] TagTemp = Values.ToArray(); 

//Convert to array 

     for (int i = 0; i < val.Length - 1; i++) 
     { 
      TempByte[i] = Convert.ToByte(TagTemp[i], 16); 
     } 

04F 출력이 올바른지 :

그것이 제 마지막 위치를 첨가

enter image description here

즉 대신 7F 467FF는 단지 준다 7.

enter image description here

너희들이 무엇을 잘못이며 어떻게 그것을 해결하기 위해 볼 수 있습니까?

+0

출력이 정확합니까? 여분의 16 진수를 어떻게 처리 할 것인가에 따라'0x04' 또는'0x4F'에서'46'을 어떻게 얻습니까? –

+0

@RogerLipscombe - '04F'는'04 46'으로 번역됩니다. 'F'는 16 진수 – Liban

+0

으로 변환되며 어떻게 "정확합니까?" '0x04F'는'79'입니다. '0x04'는'4'입니다. '0x4F'는 여전히'79'입니다. '0x04F'에서'04 46'을 어떻게 얻습니까? 내가 익숙한 어떤 번호 체계에서도 이런 일은 일어나지 않는다 ... –

답변

2
 string data = " %04F%02%BC%94%BA%15%E3%AA%08%00%7FF%00"; 

    // You need to pick an encoding -- are these things ASCII? 
    var encoding = Encoding.ASCII; 
    var values = new List<byte>(); 

    // Walk over the data (note that we don't increment here). 
    for (int i = 0; i < data.Length;) 
    { 
     // Is this the start of an escaped byte? 
     if (data[i] == '%') 
     { 
      // Grab the two characters after the '%'. 
      var escaped = data.Substring(i + 1, 2); 
      //Console.WriteLine(escaped); 

      // Convert them to a byte. 
      byte value = Convert.ToByte(escaped, 16); 
      values.Add(value); 

      // Increment over the three characters making up the escaped byte. 
      i += 3; 
     } 
     else 
     { 
      // It's a non-escaped character. 
      var plain = data[i]; 
      //Console.WriteLine(plain); 

      // Convert it to a single byte. 
      byte[] bytes = encoding.GetBytes(new[] { plain }); 
      Debug.Assert(bytes.Length == 1); 
      byte value = bytes[0]; 

      values.Add(value); 

      // Increment over that character. 
      i += 1; 
     } 
    } 

    // Print it out, in hex, separated by commas. 
    Console.WriteLine(string.Join(", ", 
         values.Select(v => string.Format("{0:X2}", v)))); 

    // Alternatively... 
    Console.WriteLine(BitConverter.ToString(values.ToArray())); 
+0

로저 감사합니다 ... 당신의 솔루션은 매우 논리입니다. 내 것이 지저분 해 .. – Liban

2

세 자리 16 진수 문자열을 한 바이트로 변환 할 수 없습니다. 1 바이트가 보관할 수있는 최대 값은 FF입니다.

1

Values[i].Replace(Values[i].Substring(2, 1), string.Empty); 교체 양의 F보다는되는 단지 하나

String.Replace()

는 대체 위치의 예를 참조 this post.

+0

인덱스''substring (2,1)'은 세번째 자리를 가리 킵니다. 또한 추가 문자가 추가되었을 때 잘 작동합니다. 위와 같은 다른 위치. – Liban

+0

MSDN 링크를 참조하십시오. 제공된 :'String.Replace()'는이 인스턴스의 지정된 유니 코드 문자가 지정된 다른 유니 코드 문자로 대체 된 새 문자열을 반환합니다. 'Substring (2,1)'은 F를 찾는다. Replace()는 그것들을 모두 대체한다. – qujck