The first thing is splitting the string. This can be accomplished easily using a for
loop and Skip()
and Take()
. I went with this method because if your string length isn't a multiple of 4 Substring()
will not catch any end characters. Also, I used a List<string>
for the split as I don't know if the input string is a fixed length or not. If it is a fixed length, you could easily replace it with a string[]
.
var splitted = new List<string>();
for(int i = 0; i < a.Length; i += 4)
{
var s = new string(a.Skip(i).Take(4).ToArray());
splitted.Add(s);
}
Then you can parse your numbers into integers and do your calculations on each number and store them into a new List<int>
var numbers = new List<int>();
foreach (var item in splitted)
{
var n = int.Parse(item, System.Globalization.NumberStyles.HexNumber);
int result = // Do whatever you need to do to each number.
numbers.Add(result);
}
After that, you can just loop through the numbers and use a StringBuilder
to rebuild the string.
StringBuilder sb = new StringBuilder();
foreach(var item in numbers)
{
sb.Append(item.ToString("X"));
}
Then just call
sb.ToString();
to get your resultant string.
If you need the numbers directly to do math, you can just store the numbers in the numbers
list instead and do your calculations as you want. Then you can loop through the results of those calculations in the final foreach
loop instead to get your rebuilt string.