If you need to use actual text, like "<stx>", in your string to represent a control character, as other solutions have suggested, you'll need to write a parser.
If, instead, you are unfamiliar with representing them in C# strings, you can use the following:
ConvertStringToHex("\x0002\x0002000000000001000\x001C1000\x001C\x001C+0\x001C941\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C\x001C00\x001C\x001C\x001C\x0003")
Assuming your string is truly limited to code points from 0-255, and you don't need to parse text like "<stx>", the following will do what you need:
public static string ConvertStringToHex(string asciiString)
{
var builder = new StringBuilder(asciiString.Length * 3);
foreach (char c in asciiString)
if (c < byte.MinValue || c > byte.MaxValue)
throw new ArgumentException(null, nameof(asciiString));
else
builder.AppendFormat("{0:X2} ", (byte)c);
if (builder.Length > 0)
builder.Length--;
return builder.ToString();
}
There are a few things to note in this code.
First, your original code built a string by repeated concatenation. This is a bad idea. A string builder is much more efficient for this sort of operation.
Second, your original code jumped through an awful lot of hoops to get a number from a character. This is unnecessary. You can directly cast a
char
to most numeric types.
Finally, just in case code points beyond the 0-255 range slip into one of your strings, I added a check and throw an exception to alert the consumer.