tags:

views:

263

answers:

3

Hi,

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

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

But I am using int instead of string values. Is it possible to do that. Therefore int test = 12345; Need to get the converted i = 3132333435

A: 

Convert Char to ASCII

int c = (int)'a';
Mendy
Sorry just made edits to the question itself
SA
Need to convert ascii to hex
SA
int hex = digit + 0x30;
Anders K.
+2  A: 

Test this

string input = "12345";
string hex = string.Join(string.Empty, input.Select(c => ((int)c).ToString("X")).ToArray());

Console.WriteLine(hex);

Note: in C# 4, the call to .ToArray() is not necessary because the string.Join method has been overloaded to accept IEnumerable<T>.

Anthony Pegram
A: 

Similair to Anthony Pegram's solution but more LINQ'ish and a tad shorter, but slower du to multiple string allocations in the aggregate method.

string hex = input.Select(c => ((int)c).ToString("X")).Aggregate((a, s) => a + s);
Roger Alsing
Thanks for the great solution.
SA