我有一个客户端 - 服务器架构,客户端在Windows上的C#和Linux上的C ++服务器上。我目前正在网络上发送一个整数作为字节,由服务器接收,然后作为字节回送给客户端。
我正在使用
构建字节数组 byte[] rotationBytes = new byte[4];
rotationBytes[0] = (byte) (rotation >> 24);
rotationBytes[1] = (byte)(rotation >> 16);
rotationBytes[2] = (byte)(rotation >> 8);
rotationBytes[3] = (byte)(rotation);
在服务器上,它是使用
构建的 char data[4];
udp::endpoint senderEndpoint;
size_t length = udpSocket.receive_from(boost::asio::buffer(data, 4), senderEndpoint);
int rotation = (int)(data[0] << 24 |
data[1] << 16 |
data[2] << 8 |
data[3]);
当服务器收到某些值时,它会输出不正确的值,但是当在前端打印出该值时,它就是预期的值。下面是一个例子。
Send from C# front end: 45
C++ server receives: 45
Send from C# front end: 90
C++ server receives: 90
Send from C# front end: 135
C++ server receives: -121
Send from C# front end: 180
C++ server receives: -76
Send from C# front end: 225
C++ server receives: -31
Send from C# front end: 270
C++ server receives: 270
有些数据是正确的,有些则不是。我做错了吗?
答案 0 :(得分:5)
似乎您的char
已签名,因此在转换为int
时会进行符号扩展。
使用unsigned char
可以更好地工作。