开发者

Need to convert ascii value to hex value

开发者 https://www.devze.com 2022-12-27 21:20 出处:网络
I need to convert ascii to hex values. Refer to the开发者_高级运维 Ascii table but I have a few examples listed below:

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


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>.

The above will work for real ASCII, because the first 128 code points of UTF16 (the encoding used in C#'s string type) have the same numeric values as for ASCII, and so casting the C# char value to int is fine. However, often what is described as "ASCII" is really some ANSI code page (in the US, usually code page 1252, "Western European (Windows"), which has 256 code points, the second 128 not having the same values as that used in UTF16.

If you are dealing with that, or any other code page for that matter, and you have the text as a C# string, you can apply the same technique as above, except using the Encoding class to convert the C# string object to a byte[] before converting to hexadecimal:

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


Convert Char to ASCII

int c = (int)'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);


Try using this method

public static string AsciiToHexadecimal(List<int> asciiList)
{
        return asciiList.Aggregate("", (current, i) => current + $"{i:X}");
}

this's a method will help you to convert an array of ASCII numbers to Hexadecimal.

0

精彩评论

暂无评论...
验证码 换一张
取 消