0

目前我有 ac# tcpclient 和一个 c++ tcpserver,但我只能从服务器端的流中读取字符,因此所有数据都将转换为字符。由于c++ char是一个有符号的8位整数,而c#客户端发送的字节是无符号的8位整数,所以服务器端无法正确接收客户端发送的所有>=128的数据。例子:

        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();

这是在客户端,我将在服务器端收到的内容打印为带符号的 int:如果我发送一个其 ascii 代码 = 136 的字符,它将变为 2 个字节:0,136。但在服务器端,它打印 0, -22。那么有没有办法让 c++ 流读取 unsigned char?还是有其他方法可以解决这个问题?感谢您的帮助!

4

2 回答 2

1

您通过 TCP 连接获得的只是原始数据,您选择解释它的方式决定了它的外观。

最简单的解决方案可能是在打印/使用之前将其转换为:

signed char val = -22;               // emulate receipt of signed char.
printf ("%d\n", (unsigned char)val); // cast to change interpretation.
于 2013-06-18T04:52:09.837 回答
0

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.

于 2013-06-18T06:14:38.290 回答