views:

98

answers:

3

Hi,

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"

+4  A: 

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
Jim Schubert
You need to format using hex.
Matthew Flaschen
Thanks Matthew, I edited to include hex conversion
Jim Schubert
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!
Jim Schubert
+2  A: 
string.Join("", from c in "12345" select ((int)c).ToString("X"));
Matthew Flaschen
snazzy... doesn't even look like C# anymore.
Mark
That is a very interesting statement. I don't think the guys at my work would understand it (they were stuck in .NET 1.1 until about 6 months ago).
Jim Schubert
+1  A: 

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