Suppose I have this string
string str = \"1234\"
I need a function that convert this string to this string:
\"0x31 0x32 0x33
This seems the job for an extension method
void Main()
{
string test = "ABCD1234";
string result = test.ToHex();
}
public static class StringExtensions
{
public static string ToHex(this string input)
{
StringBuilder sb = new StringBuilder();
foreach(char c in input)
sb.AppendFormat("0x{0:X2} ", (int)c);
return sb.ToString().Trim();
}
}
A few tips.
Do not use string concatenation. Strings are immutable and thus every time you concatenate a string a new one is created. (Pressure on memory usage and fragmentation) A StringBuilder is generally more efficient for this case.
Strings are array of characters and using a foreach on a string already gives access to the character array
These common codes are well suited for an extension method included in a utility library always available for your projects (code reuse)