Luke Justin Evans
Luke Justin Evans

Reputation: 1

C# Message Encoding / Decoding and Reverse Array

I am trying to decode and reverse a message from another IP, but it doesn't seem to work. When the message is sent it displays "System.Char[]" upon being reversed by converting the string to an array and reversing it. My next goal for this is to then decode it using a method beyond this snippet. If this is really obvious I am sorry, I am a new C# programmer and classed as a "Script Kiddie".

    private void MessageCallBack(IAsyncResult aResult)
    {
        try
        {
            int size = sck.EndReceiveFrom(aResult, ref epRemote);
            if (size > 0)
            {
                byte[] receivedData = new byte[1464];
                receivedData = (byte[])aResult.AsyncState;
                ASCIIEncoding eEncoding = new ASCIIEncoding();
                string receivedMessage = eEncoding.GetString(receivedData);

                char[] rMessage = (receivedMessage.ToCharArray());
                Array.Reverse(rMessage);

                listMessage.Items.Add("Anonymous: " + rMessage);
            }

            byte[] buffer = new byte[1500];
            sck.BeginReceiveFrom(buffer,
                0,
                buffer.Length,
                SocketFlags.None,
                ref epRemote,
                new AsyncCallback(MessageCallBack),
                buffer);
        }
        catch (Exception exp)
        {
            MessageBox.Show(exp.ToString());
        }
    }

Upvotes: 0

Views: 1149

Answers (1)

John D
John D

Reputation: 1637

In this line

listMessage.Items.Add("Anonymous: " + rMessage);

it will try to convert rMessage to a string. It will look for a ToString method and the only one it will find is Object.ToString. This just returns a string displaying the type of the object which in this case is System.Char[].

To convert rMessage to a string use new string(rMessage). This invokes the string constructor which does accept a char[].

There are some other issues. Why do you want to reverse the bytes? If the bytes were just delivered in reverse order, you are better off reversing the byte[] before converting to a string. If you are transferring data between a Little-Endian and Big-Endian machine, it's a bit more complicated: see How to get little endian data from big endian in c# using bitConverter.ToInt32 method?

Also, what do the bytes represent? Are they just extended ASCII (0-255)? Or UTF-8 or Unicode (UTF-16). To convert to a string, you need to know what encoding type to use.

If the bytes represent a UTF8 string, use utf8String = Encoding.UTF8.GetString(receivedData) and so on.

ASCII encoding is only 7 bits (0-127) so if one of your bytes is 128 or greater it will be converted to '?'.

See How to convert byte[] to string?

Upvotes: 1

Related Questions