Need to convert ascii value to hexadecimal value

I need to convert ascii to hex values. Refer to the Ascii table, but I have several 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 this. Therefore int test = 12345; You need to get the transformed i = 3132333435

+2


a source to share


3 answers


check it

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

Console.WriteLine(hex);

      

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

.



The above will work for real ASCII, because the first 128 UTF16 codepoints (the encoding used in the C # type string

) have the same numeric values ​​as for ASCII, and therefore the C # char

t24> value is fine. However, often what is described as "ASCII" is actually some ANSI code page (in the US, usually code page 1252, "Western Europe (Windows"), which has 256 code points, the second 128 does not have the same values. as used in UTF16.

If you are dealing with this, or any other code page, and you have text as C # string

, you can apply the same method as above, except using a class Encoding

to convert the C # string

object before byte[]

before converting to hex:

string input = "12345";
// Replace 1252 with whatever code page you're using, if not that one
string hex = string.Join(string.Empty,
    Encoding.GetEncoding(1252).GetBytes(input).Select(b => b.ToString("X")).ToArray());

Console.WriteLine(hex);

      

+6


a source


Convert Char to ASCII



int c = (int)'a';

      

0


a source


Similair for Anthony Pegram's solution, but more LINQ'ish and slightly shorter but slower for multiple row distributions in an aggregated method.

string hex = input.Select(c => ((int)c).ToString("X")).Aggregate((a, s) => a + s);

      

0


a source







All Articles