0
votes

Currently I have a c# tcpclient and a c++ tcpserver, but I can only read chars from the stream at the server side thus all the data will be casted to char. Since c++ char is a signed 8-bit integer, but c# client sends byte, which is unsigned 8-bit integer, so all the data >=128 sent from client cannot be received correctly at server side. Example:

        char[] textChars = text.ToCharArray();
        byte[] textBytes = new byte[textChars.Length *2];
        byte low;
        byte high;
        UInt16 current;
        for (int i = 0; i < textChars.Length; i++)
        {
            current = (UInt16)textChars[i];
            high = (byte)(current / 256);
            low = (byte)(current % 256);
            textBytes[i * 2] = high;
            textBytes[i * 2 + 1] = low;
        }

        currentStream.Write(textBytes, 0, textBytes.Length);
        currentStream.Flush();

This is at client side, and I print out what I received at server side as a signed int: if i send a char with its ascii code = 136, which will become 2 bytes:0,136. but at server side, it prints 0, -22. So is there a way to have c++ stream read unsigned char? or is there another way to solve this? Thanks for helping!

2
You can re-cast received chars to byte by (unsigned char)fatihk

2 Answers

1
votes

All you're getting over the TCP connection is raw data, it's how you choose to interpret it that decides what it looks like.

Easiest solution is to probably cast it before printing/using with something like:

signed char val = -22;               // emulate receipt of signed char.
printf ("%d\n", (unsigned char)val); // cast to change interpretation.
0
votes

Your code is broken.

char[] textChars = text.ToCharArray();
....
for (int i = 0; i < textChars.Length; i++)
{
    current = (UInt16)textChars[i];

the elements of "textChars" are of type "char". that means they contain a value between 0-255. On the next line, you do:

    high = (byte)(current / 256);

this can only ever evalute to 0.