0

I am trying to convert Hex string to ASCII in c# using visual studio community 2017. My Hex string looks like below

070196000008220031CE4745542073776964FD48

when i convert it into ASCII it looks like below

enter image description here

my confusion is why it is showing ASCII "\a" for hex "07"?? it should be . ASCII value for hex "01" should be but it showing "\u0001". It is same for ASCII control characters and extended ASCII charecters.

Can someone explain please! Am i missing anything and how to get like that.

The code i am using to convert hextoascii

    public string ConvertHextoASCII(String hexString)
    {
        try
        {
            string ascii = string.Empty;

            for (int i = 0; i < hexString.Length; i += 2)
            {
                String hs = string.Empty;

                hs = hexString.Substring(i, 2);
                int decval = System.Convert.ToInt32(hs, 16);
                char character = System.Convert.ToChar(decval);
                ascii += character;
            }
            return ascii;
        } 
        catch (Exception ex) { Console.WriteLine(ex.Message); }

        return string.Empty;
     }

Thanks in advance.

verendra
  • 223
  • 3
  • 18
  • [Convert string of integers to ASCII chars](https://stackoverflow.com/a/53791357/7444103). But, what kind of results are you expecting from that string content? Most of its content can't be translated to a printable ASCII char. – Jimi Jan 23 '19 at 15:14
  • Also, your data is not ASCII but that's okay because .NET doesn't use ASCII. It uses the UTF-16 character encoding of the [Unicode](http://www.unicode.org/charts/nameslist/index.html) character set. There is a problem, though, in that you are taking two hex digits at a time and interpreting them as an UTF-16 code unit (which requires two bytes/four digits in an agreed-upon order). Consider the Encoding classes to convert bytes to String. – Tom Blodget Jan 23 '19 at 15:42
  • this sequence of ASCII characters will be sent to hardware as a command to get response. when i send this sequence"-"É7GET swid ýH". I am getting response from hardware in terminal. I am trying to do the same with C# program. – verendra Jan 23 '19 at 15:43
  • This is an information that surely needs to be specified in the question. In **Bold**. Read what Tom Blodget wrote, what you need to change is all there. – Jimi Jan 23 '19 at 16:46

1 Answers1

1

Certain characters can be escaped in a way besides \u1234 if they're in a string literal. The \a corresponds to the "Bell (alert)" character - Unicode (and ASCII) code point 7 (0x0007). The debugger appears to prefer these alternate escapes over the \u1234 format when possible. Here's the full list of escape sequences in C# string literals.

Joe Sewell
  • 6,067
  • 1
  • 21
  • 34