I have a data string data2 = " %04%02%BC%94%BA%15%E3%AA%08%00%7F%00";
I am trying to split every two digits between the %
sign and put it into an array.
In addition to that, if there is extra digit, i.e. more than 2 digits, convert to Hex and add it to the array.
My code is working sometimes, but when I add extra digit in the second last position, it gives wrong values.
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);
}
When extra digit is added to the first position, i.e 04F
, the output is correct:
When it is added second last position, i.e 7FF
instead of 7F 46
it gives just 7
.
Do you guys see what is wrong and how to fix it?