Need to convert string/char to ascii values

2019-06-18 06:58发布

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条回答
干净又极端
2楼-- · 2019-06-18 07:33
string s = "abc123";
foreach(char c in s)
{
   Response.Write((int)c + ",");
}
查看更多
淡お忘
3楼-- · 2019-06-18 07:46

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
查看更多
Luminary・发光体
4楼-- · 2019-06-18 07:51
string.Join("", from c in "12345" select ((int)c).ToString("X"));
查看更多
相关推荐>>
5楼-- · 2019-06-18 07:53

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 :)

查看更多
登录 后发表回答