is there a nicer what to convert Hex response to character

Gerald Oakham 101 Reputation points

I am writing a socket interface, and I can send a message

                byte[] messageSent = { 0x00, 0x02, 0x40, 0x46, 0x46, 0x46, 0x46, 0x03 };  
                //                                         ^             (STX)@FFF{ETX)               ^  

and get a reply back, however, the reply back is

Now, this is returns the value 06 (with is correct )

                // Data buffer  
                byte[] messageReceived = new byte[1024];  
                // We receive the message using the method Receive(). This method returns number of bytes received, that we'll use to convert them to string  
                int byteRecv = sender.Receive(messageReceived);  
                string returndata = BitConverter.ToString(messageReceived, 0, byteRecv);  

as this is Ascci control char, 0X06 = ACK.
If there a way to display ACK instead of 06 ( or ♠ , or any other control char) better than

if (returndata == "06")  
returndata = "ACK"  

Thank you

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
3,810 questions
{count} votes

Accepted answer
  1. Michael Taylor 41,766 Reputation points

    What you consider to be ACK is just a convenient name for the actual key. Sort of like you consider \r to be CR. If you want this kind of translation then put it into a dictionary that maps the bytes to strings. When you get a value back check in the dictionary first. If you don't find it then convert to a string as normal. Note that this would preclude using BitConverter.ToString in most cases unless you first ran it through that function and then converted from there. It would be easier to just do the conversion yourself. That is what Encoding is for. But it would be inefficient as you are mucking with strings. Ideally if you're on .NET 5+ then use the span overrides instead. Otherwise it might just be easier to use simple char casting.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Gerald Oakham 101 Reputation points

    Thank you both for your prompt replies.
    I'll stop barking up this tree then :-)

    0 comments No comments