通过插座在C 和Python之间进行固定的浮点阵列
Exchange fixed float array between C++ and python through socket
我正在尝试使用c 发送固定长度的float数组并使用python
这是我的C 客户端,其中Sconnect是套接字对象
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#@'
如何将其恢复回我发送的原始浮点数据?还是有更好的方式发送和接收数据?
您可以使用struct模块解开字节数据。
import struct
news = struct.unpack('ff', b'x9ax99x99?nxd7#@')
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浮子。有关其他格式字符,请参见https://docs.python.org/3/library/struct.html。
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- OpenMP阵列性能较差
- 最接近的字符串:在字符串阵列中找到2个字符串之间的最小距离
- 两个未分类阵列之间的最小差异
- 通过插座在C 和Python之间进行固定的浮点阵列
- 阵列C 中两个点函数之间的距离
- Qthread char阵列在两个线程之间传递后被摧毁
- 线性阵列和多维之间有什么区别
- 为什么我会看到在堆和堆栈上分配的阵列之间的不同行为
- 指针阵列和指针数组的指针之间的区别
- char阵列[]和char *数组之间有什么区别
- 相同大小的2D和1D阵列之间的内存或执行问题
- 在结构阵列(AoS)和阵列结构(SoA)之间来回切换
- 在Java Android和JNI之间发送/接收音频阵列
- 阵列和阵列堆栈之间的区别
- 多暗对象的多暗阵列和仅包含一个暗对象的一个较高暗的阵列之间的区别是什么
- 基于组件的游戏对象的阵列和地图之间的优点和缺点
- 创建一个3x3x3阵列.用0到9之间的随机值填充.输出数组.找出3个最小值和3个最大值的输出
- 使用多晶型载体与多晶型阵列之间的差异