gpt4 book ai didi

python - 通过套接字在C++和python之间交换固定 float 组

转载 作者:行者123 更新时间:2023-11-28 05:16:07 24 4
gpt4 key购买 nike

我正在尝试使用 C++ 发送固定长度的 float 组并使用python获取它

这是我的 C++ 客户端,其中 sConnect 是一个 SOCKET 对象

    float news[2];
news[0] = 1.2;
news[1] = 2.56;
char const * p = reinterpret_cast<char const *>(news);
std::string s(p, p + sizeof news);
send(sConnect, &s[0], sizeof(news), 0);

并且在 python 服务器我的代码就像

import socketserver


class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):

self.data = self.request.recv(8).strip()
print (self.data)

if __name__ == "__main__":
HOST, PORT = "127.0.0.1", 9999
print("listening")
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()

而我在python得到的数据是这样的

b'\x9a\x99\x99?\n\xd7#@'

如何将其恢复为我发送的原始 float 据?或者是否有更好的方式来发送和接收数据?

最佳答案

您可以使用结构模块来解压字节数据。

import struct
news = struct.unpack('ff', b'\x9a\x99\x99?\n\xd7#@')
print(news)

使用您的代码:

import struct
import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(8).strip()
news = struct.unpack('ff', self.data)
print(news)

struct.unpack 的第一个参数“ff”是指定数据预期布局的格式字符串,在本例中为 2 个 float 。参见 https://docs.python.org/3/library/struct.html对于其他格式字符。

关于python - 通过套接字在C++和python之间交换固定 float 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42610090/

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