Question

With this function I convert received bytes into unicode string:

//MESSAGE READER
String message = null;
byte[] b = new byte[2048];
int k = Socket.Receive(b);
char c = ' ';
for (int i = 0; i < k - 1; i++)
{
    c = Convert.ToChar(b[i]);
    message += c.ToString();
}

How can I convert it to UTF-8 string instead of unicode?

EDIT:
Convert.ToChar - Converts the value of the specified 8-bit unsigned integer to its equivalent Unicode character.
Is there some function that converts to equivalent UTF-8 character?

Was it helpful?

Solution 2

If your incoming data is in UTF-8 format, then you can just pass the byte array directly to Encoding.UTF8.GetString to get the string representation of the UTF-8 data.

byte[] b = new byte[2048];
int k = Socket.Receive(b);    
string message = Encoding.UTF8.GetString(b, 0, k);

OTHER TIPS

Encoding.UTF8.GetString(Encoding.Unicode.GetBytes(message));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top