gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:34:20 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com