6

I need to convert char to hex values. Refer to the Ascii table but I have a few examples listed below:

  • char 1 = 31 2 = 32 3 = 33 4 = 34 5 = 35 A = 41 a = 61 etc

Therefore string str = "12345"; Need to get the converted str = "3132333435"

SA.
  • 61
  • 1
  • 1
  • 2

4 Answers4

9

I think this is all you'll need:

string finalValue;
byte[] ascii = Encoding.ASCII.GetBytes(yourString);
foreach (Byte b in ascii) 
{
  finalValue += b.ToString("X");
}

More info on MSDN: http://msdn.microsoft.com/en-us/library/system.text.encoding.ascii.aspx

Edit: To Hex:

string finalValue;
int value;
foreach (char c in myString)
{
  value = Convert.ToInt32(c);
  finalValue += value.ToString("X"); 
  // or finalValue = String.Format("{0}{1:X}", finalValue, value);
}
// use finalValue
Joseph Yaduvanshi
  • 20,241
  • 5
  • 61
  • 69
  • At first, I didn't understand the hex comment, so I rewrote it. This morning SO told me the comment was new so I look again, and I just forgot the conversion modifier in ToString(). So, this is two ways to get what you want. If I had used Convert.ToByte, the second block would be redundant! – Joseph Yaduvanshi Apr 24 '10 at 13:58
3
string.Join("", from c in "12345" select ((int)c).ToString("X"));
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
3
string s = "abc123";
foreach(char c in s)
{
   Response.Write((int)c + ",");
}
G.M. Patel
  • 51
  • 5
1

To get it in a single line, and more readable (imo)

var result = "12345".Aggregate("", (res, c) => res + ((byte)c).ToString("X"));

this returns "3132333435", just as you requested :)

Artiom Chilaru
  • 11,811
  • 4
  • 41
  • 52