2

Possible Duplicate:
.NET Convert from string of Hex values into Unicode characters (Support different code pages)

Looking to convert a string containing an ASCII string into text, i seem to be only be able to find System.Text.ASCIIEncoding.ASCII.GetString which converts from a Byte[] but in this circumstance I would like to be able to do it from a string.

its a string containing ASCII hex: For example : ASCI = 47726168616D would equal Graham

Are there any built in functions for this? help would be appreciated, thank you.

Community
  • 1
  • 1
GrahamHull
  • 325
  • 1
  • 3
  • 12
  • 3
    What is a normal string in C#? – mloskot Apr 27 '12 at 11:27
  • 4
    @Graham Try converting string to byte[] and then apply System.Text.ASCIIEncoding.ASCII.GetString – Milee Apr 27 '12 at 11:27
  • 1
    There are not ASCII string in C#, all them are Unicode. So, where is this string coming from? –  Apr 27 '12 at 11:28
  • 1
    What exactly do you mean by `ASCII string`? Please give an example. You can use the "edit" link below your answer to extend your question. – Heinzi Apr 27 '12 at 11:29
  • The question is very vague. 1) show some code 2) tell us what do you have and what do you want to have – kuba Apr 27 '12 at 11:30
  • its a string containing ASCII hex: For example : ASCI = 47726168616D would equal Graham – GrahamHull Apr 27 '12 at 11:34
  • @JaimeOlivares - Your statement is 100% false. You can encode a string to be ASCII, if your talking about the default encoding, then I would say your statement is at most acceptable. – Security Hound Apr 27 '12 at 11:53
  • @Ramhound, you are totally confused, a string is encoded into a byte array or any other binary stream. So, when it is encoded, it is not a String object anymore. The string object doesn't have an Encoding attribute, so it is always Unicode. To enlight you more, in MSDN documentation (http://msdn.microsoft.com/en-us/library/362314fe(v=vs.100).aspx) it is stated: "The string type represents a sequence of zero or more Unicode characters. string is an alias for String in the .NET Framework" –  Apr 28 '12 at 00:54

1 Answers1

7
private static string GetStringFromAsciiHex(String input)
{
    if (input.Length % 2 != 0)
        throw new ArgumentException("input");

    byte[] bytes = new byte[input.Length / 2];

    for (int i = 0; i < input.Length; i += 2)
    {
        // Split the string into two-bytes strings which represent a hexadecimal value, and convert each value to a byte
        String hex = input.Substring(i, 2);
        bytes[i/2] = Convert.ToByte(hex, 16);                
    }

    return System.Text.ASCIIEncoding.ASCII.GetString(bytes);
}
CodeCaster
  • 147,647
  • 23
  • 218
  • 272