JeremyCC
JeremyCC

Reputation: 43

Exchange fixed float array between C++ and python through socket

I am trying to use C++ sending a fixed length float array and use python to get it

Here is my C++ client, where sConnect is a SOCKET object

    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);

And at python server my code is like

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()

And the data I got at python is like

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

How to recover this back to the original float data I sent? Or is there a better way to send and receive the data?

Upvotes: 1

Views: 590

Answers (1)

Kris
Kris

Reputation: 1438

You can use the struct module to unpack the byte data.

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

With your code:

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)

The first argument to struct.unpack, 'ff', is the format string specifying the expected layout of the data, in this case 2 floats. See https://docs.python.org/3/library/struct.html for other format characters.

Upvotes: 2

Related Questions