0

I have a device emulator which accept the data as text from socket.Below code works fine until I send from 0x00 to 0x7F means upto Ascii limit (0 to 127). Issue arise when I try to send beyond the Ascii limit like 0x80,0x81. It send to emulator 0x3F('?') and it change the whole meaning of command. because it does not able to understand this.

So What may be the possible solution to send the data beyond Ascii limit

Send data code:

 //string data = textBox1.Text;
 string d1 = ConvertHex("35");  //getting exact byte in socket             
 byte[] buffer = Encoding.ASCII.GetBytes(d1);
 clientStream.Write(buffer, 0, buffer.Length);
 clientStream.Flush();

ConverHex function:

public static string ConvertHex(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);
                uint decval = System.Convert.ToUInt32(hs, 16);
                char character = System.Convert.ToChar(decval);
                ascii += character;

            }

            return ascii;
        }
        catch (Exception ex) { Console.WriteLine(ex.Message); }

        return string.Empty;
    }
jiten
  • 5,128
  • 4
  • 44
  • 73

1 Answers1

3

but when I send more than 79 then I get 3F in emulator.

7F is in fact the upper bound. Because that's 127 in decimal, the highest code point supported by the ASCII encoding. Code points higher than that get decoded to a question mark, having the code point of 63 or 3F in hexadecimal.

That's because you're using text to transmit binary data. Don't do that. See How can I convert a hex string to a byte array? for a proper implementation of "hex string to byte array".

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • yes, you are right. Actually device emulator which is given by client, works like that.So I can not change the emulator behavior right now. I can change only my code. – jiten Jun 14 '18 at 04:25