c++ - 为什么我在通过网络发送数据时在两台机器上收到不同的值?

标签 c++ networking

我有一个客户端-服务器架构,客户端在 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

有些数据是正确的,有些则不是。我做错了什么吗?

最佳答案

似乎您的 char 已签名,因此在转换为 int 时得到符号扩展。

使用 unsigned char 可能效果更好。

关于c++ - 为什么我在通过网络发送数据时在两台机器上收到不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49016064/

相关文章:

c++ - 如何摆脱 Xcode 4 中的 "In class initializer for static data member ... is a C++0x extension"警告

python - 过滤权重低于阈值的边时出现运行时错误 - Networkx

c - 通过 TCP 传输数据总是停止在 251 传输

java - 如果它们通过 java 包装在缓冲区中,我是否必须显式关闭所有流?

c++ - clang 的行为不同于 msvc++ 和 gcc

c++ - 通过将基类强制转换为派生类并设置数据来扩展基类

c++ - boost 状态图 : How to spread across multiple files?

c - 在接受连接之前或之后 fork ?

macos - 是否有在 Docker for Mac 中使用主机网络的解决方法?

C++逻辑替代运算符