First of all, you have the wrong code type. What you are converting to is the representations in EBCDIC (
http://en.wikipedia.org/wiki/EBCDIC[
^]), not ASCII (
http://en.wikipedia.org/wiki/ASCII[
^]) which is used by Microsoft, and on most other systems. The code I am providing will only convert the first 8 bits, not the full 16 bits, but can be fixed to do that if that is what you want:
string testString = "1234ABCD";
var stringBuilder = new StringBuilder();
foreach (char chr in testString)
{
var lft = ((int) chr & 240) / 16;
stringBuilder.Append(ConvertNibbleToHex(lft));
var rt = (int) chr & 15;
stringBuilder.Append(ConvertNibbleToHex(rt));
}
This uses the following function:
private static char ConvertNibbleToHex(int value)
{
if (value < 10)
return (char) (value + 48);
return (char)(value + 55);
}